Search code examples
javajunitspring-batchmaven-surefire-plugin

Junit test fails when fetching Exception object stored in a class, not thrown


I have a listener class where I get the exception object as a stored value. The exception object is stored in a class by the framework. It is fetched in the listener later to do certain operations.

below is the actual method to be tested :

@Override
public void afterChunkError(ChunkContext chunkContext) {
    Exception e = (Exception) chunkContext.getAttribute("sb_rollback_exception"); // LINE 1
    if (e instanceof ValidationException) { // LINE 2
        logger.error(messageSource
                .getMessage("errors.maxInteger", new String[] { "Point", "1000000" }, Locale.getDefault())); 
     //insert exception details to DB.
    }
}

The junit looks something like this :

    RuntimeException runtimeException = new RuntimeException("My Run Time Exception");
    JobException exception = new JobException(runtimeException);
    Mockito.when(chunkContext.getAttribute("sb_rollback_exception")).thenReturn(exception);

It works fine as a standalone test case. mvn install fails as the test cases run by maven-surefire plugin fails saying

 Tests run: 56, Failures: 0, Errors: 1, Skipped: 0

The error is because of LINE 1 of the first block of code. What is the recommended way to test this use-case?


Solution

  • Maven may run tests in parallel. So, If you are manipulating/using a class level attribute from tests, its value could differ based on order of tests running.

    The solution to such problems is not to have junit class level attributes for test. Rather, have variables specific to each test.