java 静态类 空指针_java – 运行JUnit测试时未执行静态类初始化

我有一个带有一些静态字段的

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或通用方式)?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值