JUnit和Cobertura代码覆盖范围

时间:2016-03-21 19:26:18

标签: java junit

我正在使用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();
}

1 个答案:

答案 0 :(得分:0)

每项测试都应该是独立的。如果您无法移除静态状态(即静态字段mapper),那么您可能应该添加一个重置此字段的@Before @After方法。

覆盖范围:

  • getInstance有两个分支:如果mapper为null或不为null。您只测试一个分支
  • initialize有3种状态:mapper == null && isJsonIgnoreUnknownProperties == truemapper == null && isJsonIgnoreUnknownProperties == falsemapper != null。您只测试一个分支。

此外,您的assertNotNull(configuration)是不必要的。您应该测试initialize返回一个非空的映射器。