PowerMock + Emma – 私有静态方法和其他方法的代码覆盖率显示为0%

我参考了PowerMock: 使用PowerMockito模拟私有方法并在此处应用相同的逻辑。 另外,我在eclipse / STS中安装了EMMA(开源工具),但是当我运行代码时,我看到零%的代码覆盖率。 为什么?

public class MyClient { public void publicApi() { System.out.println("In publicApi"); int result = 0; try { result = privateApi("hello", 1); } catch (Exception e) { //Assert.fail(); } System.out.println("result : "+result); if (result == 20) { throw new RuntimeException("boom"); } } private static int privateApi(String whatever, int num) throws Exception { System.out.println("In privateAPI"); thirdPartyCall(); int resp = 10; return resp; } private static void thirdPartyCall() throws Exception{ System.out.println("In thirdPartyCall"); //Actual WS call which may be down while running the test cases } } 

MyClientTest.java

 @RunWith(PowerMockRunner.class) @PrepareForTest(MyClient.class) public class MyClientTest { @Test public void testPublicAPI() throws Exception { PowerMockito.mockStatic(MyClient.class); //PowerMockito.doReturn(10).when(MyClient.class, "privateApi", anyString(), anyInt()); PowerMockito.when(MyClient.class,"privateApi", anyString(), anyInt()).thenReturn(anyInt()); } } 

实际代码覆盖范围: 在此处输入图像描述

的pom.xml

    org.powermock powermock-api-mockito 1.7.4 test   org.powermock powermock-module-junit4 1.7.4 test   org.powermock powermock-module-junit4-rule-agent 1.7.4 test   org.powermock powermock-core 1.7.4 test   junit junit ${junit.version} test   

如果您正在构建Spy或Mock,则不会调用实际的测试代码。 间谍的目的是能够verify()它们,以便通过调用正确的回调或方法来检查代码的行为是否正确。 在模拟的情况下,重点是将代码引导到特定的控制流路径,并verify()与模拟的预期交互。

由于您的测试用例在间谍上调用测试方法,因此难怪您的代码覆盖率恰好为0%。 如果您要validation与模拟方法的交互,您可能会发现没有发生。

你要做的是设置你的模拟但是调用“正常方式”下的实际代码。 我们的想法是启动执行环境,然后“正常”调用测试的方法调用,最后观察实际发生的情况。 最后一点包括对生成的输出的正常断言,对预期的交互的validation(这些都发生了,以及这些涉及预期的参数/值)。

更改您的测试代码:

 MyClient classUnderTest = PowerMockito.spy(new MyClient()); 

至:

 MyClient classUnderTest = new MyClient(); 

并观看代码覆盖率。