gpt4 book ai didi

java - PowerMock + Emma - 私有(private)静态方法和其他方法的代码覆盖率显示为 0%

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:13 25 4
gpt4 key购买 nike

我引用了PowerMock:Mock private method using 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());
}
}

实际代码覆盖率: enter image description here

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>

最佳答案

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

由于您的测试用例调用了 spy 的测试方法,因此您的代码覆盖率恰好为 0%也就不足为奇了。如果您要验证与模拟方法的交互,您可能会发现什么都没有发生。

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

更改您的测试代码:

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

致:

MyClient classUnderTest = new MyClient();

并观察代码覆盖率。

关于java - PowerMock + Emma - 私有(private)静态方法和其他方法的代码覆盖率显示为 0%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52064126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com