I have a java class with some static fields:
private static final PDMapCacheDAO REST_CACHE_DAO =
new PDMapCacheDAOImpl( Constants.REST_CACHE_NAME );
private static final PDMapCacheDAO HOLIDAYS_CACHE_DAO =
new PDMapCacheDAOImpl( Constants.HOLIDAYS_CACHE_NAME );
private static final String[] DATE_ARRAY = { "D", "0", "1", "2", "3", "C" };
and the JUnit test mocks that initialization behaviour for REST_CACHE_DAO and HOLIDAYS_CACHE_DAO:
final PDMapCacheDAOImpl holidaysMapCacheDAOImpl = mock(PDMapCacheDAOImpl.class);
final PDMapCacheDAOImpl restMapCacheDAOImpl = mock(PDMapCacheDAOImpl.class);
whenNew(PDMapCacheDAOImpl.class).withArguments(Constants.HOLIDAYS_CACHE_NAME).thenReturn(holidaysMapCacheDAOImpl);
whenNew(PDMapCacheDAOImpl.class).withArguments(Constants.REST_CACHE_NAME).thenReturn(restMapCacheDAOImpl);
When the tests are executed individually, the tests perform as expected, but when all JUnit tests are executed together (from the Java Project with Run As --> Junit Test) the test gives an null pointer exception.
I have done some debugging and I've found out that the problem (as stated in the title) is that the static classes aren't initialized - when the static methods are invoked the REST_CACHE_DAO and HOLIDAYS_CACHE_DAO are null. The constructor of PDMapCacheDAOImpl is not invoked and the mocks are not injected, hence when we use them, it gives a NPE.
I've read about some tools to performs test, like eclemma that have this error (some static classes are not initialized). In this case the solution is to include the -f option.
This is what the Eclemma website says about this problem:"
2.8. How is class coverage defined by EMMA? First of all, a class needs to be considered executable to even be considered for coverage. An executable class is considered to have been covered if it has been loaded and initialized by the JVM. Class initialization implies that the class static constructor (if any) is executed. Note that a class can be covered even though none of its other methods has been executed. It is common to see a small number of loaded but uninitialized classes when you use emmarun without the -f option. EMMA reports class coverage so that you could spot classes that do not seem to be "touched" by your test suite: they could be either dead code or in need of more test attention.
The interesting thing is that we are not using Eclemma, we are using Cobertura, but the behaviour and the errors are the same.
Does anyone know something about this error in Cobertura and how to solve it? (Either in Cobertura or in a generic way)?
@InjectMocks
will do the trick. You'll probably have more issues with that. This is why DI frameworks like Spring, Guice or CDI were invented. – Dearth