[英]JUnit and Cobertura Code Coverage
我正在使用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();
}
每個測試應該是獨立的。 如果您不能刪除靜態狀態(即靜態字段mapper
),則可能應該添加一個@Before @After
方法來重置此字段。
對於覆蓋范圍:
getInstance
有兩個分支:如果mapper為null或不為null。 您只測試一個分支 initialize
具有3種狀態: mapper == null && isJsonIgnoreUnknownProperties == true
, mapper == null && isJsonIgnoreUnknownProperties == false
, mapper != null
。 您僅測試一個分支。 此外,您的assertNotNull(configuration)
是不必要的。 您可能應該測試initialize
返回一個不為null的映射器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.