unit-testing - 使用 PowerMockito 模拟私有 void 方法
问题描述
public class Abcd {
public String one() {
System.out.println("Inside method one");
StringBuilder sb = new StringBuilder();
two(sb);
return "Done";
}
private void two(StringBuilder sb) {
System.out.println("Inside method two");
}
}
这是测试类
@RunWith(PowerMockRunner.class)
@PrepareForTest(Abcd.class)
public class TestAbcd {
@Test
public void testMethod1() throws Exception {
Abcd abcd = PowerMockito.spy(new Abcd());
StringBuilder sb = new StringBuilder();
PowerMockito.doNothing().when(abcd, "two", sb);
abcd.one();
}
}
控制台输出:
Inside method one
Inside method two
编辑部分没有故障跟踪: 故障跟踪:
请让我知道我犯了什么错误,以及如何使它起作用。
解决方案
您需要 @PrepareForTest 注释来使用 PowerMockito 获得对私有方法的控制。
请参阅这篇文章:PowerMock 中的@PrepareForTest 真正意味着什么?
总之,测试用例应如下所示:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Abcd.class)
public class TestAbcd {
@Test
public void testMethod1() throws Exception {
Abcd abcd = PowerMockito.spy(new Abcd());
PowerMockito.doNothing().when(abcd, method(Abcd.class, "two", StringBuilder.class))
.withArguments(any(StringBuilder.class));
abcd.one();
}
}
推荐阅读
- java - Java RSA 密钥到 C# XML 密钥:将 Java 中的 RSA PublicKey 和 PrivateKey 更改为 C# XML RSAKeyValue XML 字符串?
- curl - 使用 jira rest api - 如何获取特定问题的描述?
- docker - 容器内的 docker vim 乱码
- vb.net - Process.Start 不起作用
- r - rename_at (dplyr) 失败并出现错误
- kubernetes - 如何在 kubernetes 中正确给出 POD 名称的模式?
- angular - Observable.next() 不是函数
- vbscript - 如何使用 qtp 数据表方法将日期附加到 xls 文件?
- angular - 角材料垫-自动完成打开面板
- spring-boot - 如何在测试之间关闭应用程序上下文