【发布时间】:2019-02-03 10:57:30
【问题描述】:
我从 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>
【问题讨论】:
-
您似乎准备了用于测试的静态方法(即通过
PowerMockito.mockStatic(...)和@PrepareForTest(...)操作字节码),我可以看到您正在设置测试/模拟行为(使用PowerMockito 的@ 987654329@),但@user298396 是对的 - 您的测试中似乎没有任何东西实际上正在锻炼/调用您的测试类...? -
PowerMock + ECLemma:覆盖数据损坏。习惯它。要么尝试 cobertura,要么(老实说,更好的方法):学习如何编写 易于测试 无需 PowerMock(ito) 字节码操作巫毒魔法即可测试的生产代码。
标签: java powermock powermockito