Skip to content

MockitoTestNGListener does not close session on exception in before method #88

Description

@whitelake-city

The MockitoTestNGListener does not close the session of before methods in case an exception is thrown in the before method. All follow-up tests will fail. This is a problem especially in test pipelines when you run 100s of tests. Finding the cause takes longer than necessary. In these scenarios it also appears that getting the class name from ITestResult returns null. This causes an NPE when calling hasMockitoTestNGListener.

I would propose the following solutions in the listener:

protected boolean hasMockitoTestNGListener(ITestResult testResult) {
		return nonNull(testResult.getTestClass())
				&& findAnnotation(testResult, Listeners.class)
				.map(Listeners::value)
				.map(Arrays::stream)
				.orElseGet(Stream::empty)
				.anyMatch(listener -> listener == MockitoTestNGListener.class);
}

Important part is to return true in shouldBeRunAfterInvocation in case an exception was thrown in the before method.

private boolean shouldBeRunAfterInvocation(IInvokedMethod method, ITestResult testResult) {
	return (method.isTestMethod() && hasMockitoTestNGListener(testResult))
		|| (isBeforeMethod(method) && nonNull(testResult.getThrowable()));
}

Hope this makes sense. I actually ran into the situation and applying these changes fixed it for me. With the fix I only see the tests from the same test class failing and not other tests afterwards as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions