java-PowerMock Emma-私有静态方法和其他方法的代码覆盖率也显示0%
作者:互联网
这个问题已经在这里有了答案: > PowerMock ECLEmma coverage issue 7个
我从:Mock private method using PowerMockito获取了PowerMock的引用,并在此处应用了相同的逻辑.另外,我在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
<dependencies>
<!-- Power Mock -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule-agent</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
解决方法:
如果要构建间谍程序或模拟程序,则不会调用实际的测试代码.间谍的目的是为了能够验证()它们,以便通过调用正确的回调或方法来检查代码是否正常运行.在模拟的情况下,重点是将代码引导至特定的控制流路径,并验证()与模拟的预期交互作用.
由于您的测试用例在一个间谍上调用了测试方法,因此,难怪您的代码覆盖率恰好是0%.如果要验证与模拟方法的交互,您可能会发现没有任何反应.
相反,您要做的是设置模拟程序,但以“正常方式”调用测试中的实际代码.想法是准备执行环境,然后“正常”调用经过测试的方法,最后观察实际发生的情况.最后一点包括对产生的输出的正常声明,对预期交互的验证(既发生了交互,又涉及预期的参数/值).
更改测试代码:
MyClient classUnderTest = PowerMockito.spy(new MyClient());
至:
MyClient classUnderTest = new MyClient();
并观看代码覆盖范围.
标签:powermockito,java,powermock 来源: https://codeday.me/bug/20191009/1878219.html