我有一个带有一些静态字段的
java类:
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" };
并且JUnit测试模拟了REST_CACHE_DAO和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);
当单独执行测试时,测试按预期执行,但是当所有JUnit测试一起执行时(从带有运行方式的Java项目 – > Junit测试),测试会给出空指针异常.
我做了一些调试,我发现问题(如标题中所述)是静态类未初始化 – 当调用静态方法时,REST_CACHE_DAO和HOLIDAYS_CACHE_DAO为空.不调用PDMapCacheDAOImpl的构造函数并且不注入模拟,因此当我们使用它们时,它会给出一个NPE.
我已经阅读了一些执行测试的工具,比如eclemma有这个错误(一些静态类没有初始化).在这种情况下,解决方案是包含-f选项.
这就是Eclemma网站关于这个问题所说的:“
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.
有趣的是,我们没有使用Eclemma,我们正在使用Cobertura,但行为和错误是相同的.
有没有人知道Cobertura中的这个错误以及如何解决它? (在Cobertura或通用方式)?