簡體   English   中英

JUnit和Cobertura代碼覆蓋率

[英]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 == truemapper == null && isJsonIgnoreUnknownProperties == falsemapper != null 您僅測試一個分支。

此外,您的assertNotNull(configuration)是不必要的。 您可能應該測試initialize返回一個不為null的映射器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM