测试用例未覆盖cobertura

时间:2017-02-05 05:08:27

标签: java unit-testing junit4 testcase powermockito

public class MyUtil {
    public static Properties loadProperties() throws Exception {
        Properties prop = new Properties();
        InputStream inputStream = MyUtil.class.getClassLoader().getResourceAsStream(PROPERTY_FILENAME);
        if (inputStream != null) {
            prop.load(inputStream);
        }
        return prop;
    }
}

我已经为上述方法编写了测试用例,当我在eclipse中作为测试用例运行时,我调试loadProperties()时未调用cobertura report显示为未覆盖代码。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ MyUtil.class, Properties.class })

@Test
public void testLoadProperties() throws Exception{
    String fileName = "application.properties";
    Properties mockProps = PowerMockito.mock(Properties.class);
    PowerMockito.mockStatic(Properties.class);
    PowerMockito.whenNew(Properties.class).withNoArguments().thenReturn(mockProps);
    InputStream mockInputStream = Mockito.mock(InputStream.class);
    PowerMockito.mockStatic(MyUtil.class);
    ClassLoader mockClassLoader = Mockito.mock(ClassLoader.class);
    PowerMockito.when(MyUtil.class.getClassLoader()).thenReturn(mockClassLoader);
    PowerMockito.when(mockClassLoader.getResourceAsStream(fileName)).thenReturn(mockInputStream);
    PowerMockito.doNothing().when(mockProps).load((InputStream)Mockito.any());
    MyUtil.loadProperties();
    //assertNotNull("Not Null", MyUtil.loadProperties()); //assert failing
}

我应该更改什么以确保我的代码实际涵盖代码覆盖率?

1 个答案:

答案 0 :(得分:1)

PowerMock打破代码覆盖率工具这是众所周知的老问题:
https://github.com/cobertura/cobertura/issues/94

目前,只有一种方法可以获得JaCoCo Offline的代码覆盖率 https://github.com/powermock/powermock/wiki/Code-coverage-with-JaCoCo