我从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 :(得分:0)
如果您要构建间谍程序或模拟程序,则不是在调用测试中的实际代码。间谍的重点是能够verify()
进行间谍活动,以便通过调用正确的回调或方法来检查代码是否正确运行。对于模拟,关键是将代码引导到特定的控制流路径,并verify()
与模拟进行预期的交互。
由于您的测试用例在一个间谍上调用了测试方法,因此也就不足为奇了,您的代码覆盖率恰好是0%。如果要验证与嘲笑方法的交互,您可能会发现没有任何反应。
您要做的是设置模拟程序,但以“正常方式”调用测试中的实际代码。想法是准备执行环境,然后“正常”调用经过测试的方法,最后观察实际发生的情况。最后一点包括对产生的输出的常规断言,预期交互的验证(既发生了交互,又涉及预期的参数/值)。
更改测试代码:
MyClient classUnderTest = PowerMockito.spy(new MyClient());
收件人:
MyClient classUnderTest = new MyClient();
并观看代码覆盖范围。