我正在使用JUnit
测试两个方法,我面临的问题是,如果我单独运行测试用例,但第二个测试总是失败并抛出我期待的RuntimeException
如果我一起运行它们对于第二种方法,我正在测试Null
条件,因此我期待RuntimeException
,对于第一种方法,我正在测试第二个if
块,它采用boolean
而我是设置它。到目前为止,Line Coverage
为81%,Branch Coverage
为66%,但我不确定我在测试用例中做错了什么,因为我没有获得全线和分支覆盖率。
待测班级:
private static ObjectMapper mapper;
public static ObjectMapper initialize( ClientConfiguration config ) {
if( mapper == null ) {
synchronized (ObjectMapperHolder.class) {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true);
//Allows Users to overwrite the Jackson Behavior of failing when they encounter an unknown property in the response
if( config.isJsonIgnoreUnknownProperties() ) {
mapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
}
}
}
return mapper;
}
public static ObjectMapper getInstance() {
if( mapper == null ) {
throw new RuntimeException( "The initialize() method must be called before the ObjectMapper can be used" );
}
return mapper;
}
JUnits:
@Test
public void testInitialize() throws Exception {
ClientConfiguration configuration = new ClientConfiguration();
configuration.setJsonIgnoreUnknownProperties(true);
ObjectMapperHolder.initialize(configuration);
assertNotNull(configuration);
}
@Test(expected=RuntimeException.class)
public void testGetInstance() throws Exception {
ObjectMapperHolder.getInstance();
}
答案 0 :(得分:0)
每项测试都应该是独立的。如果您无法移除静态状态(即静态字段mapper
),那么您可能应该添加一个重置此字段的@Before @After
方法。
覆盖范围:
getInstance
有两个分支:如果mapper为null或不为null。您只测试一个分支initialize
有3种状态:mapper == null && isJsonIgnoreUnknownProperties == true
,mapper == null && isJsonIgnoreUnknownProperties == false
,mapper != null
。您只测试一个分支。此外,您的assertNotNull(configuration)
是不必要的。您应该测试initialize
返回一个非空的映射器。