java - PowerMockito mockStatic 带输入
问题描述
我需要模拟一个具有输入参数的静态方法。对于类中的其他函数,必须调用原始方法,而对于我试图模拟的函数,必须执行模拟的存根。我尝试了以下代码,但它没有按预期工作。
public class Foo {
public static String static1() {
System.out.println("static1 called");
return "1";
}
public static String static2() {
System.out.println("static2 called");
return "2";
}
public static String staticInput(int i) {
System.out.println("staticInput called");
return "static " + i;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class })
public class TestMockito {
@Test
public void test() throws Exception {
PowerMockito.mockStatic(Foo.class, Mockito.CALLS_REAL_METHODS);
PowerMockito.doReturn("dummy").when(Foo.class ,"static1");
PowerMockito.when(Foo.staticInput(anyInt())).thenAnswer(invocation -> {
System.out.println((int)invocation.getArgument(0));
return "staticInput mock";
});
// PowerMockito.doAnswer(new Answer() {
// @Override
// public Object answer(InvocationOnMock invocation) throws Throwable {
// int i = (int) invocation.getArguments()[0];
// System.out.println(i);
// return i;
// }
//
// }).when(Foo.staticInput(anyInt()));
System.out.println(Foo.static1());
System.out.println(Foo.static2());
System.out.println(Foo.staticInput(7));
}
}
我得到以下输出:
staticInput called dummy static2 called 2 staticInput called static 7
解决方案
我想出的最简洁的代码是明确地标记应该转发到它们实际实现的方法。
PowerMockito.mockStatic(Foo.class);
PowerMockito.doReturn("dummy").when(Foo.class, "static1");
PowerMockito.when(Foo.static2()).thenCallRealMethod();
PowerMockito.when(Foo.staticInput(anyInt())).thenAnswer(invocation -> {
System.out.println((int)invocation.getArgument(0));
return "staticInput mock";
});
输出(符合我的期望):
dummy
static2 called
2
7
staticInput mock
奇怪的是,我的原始代码输出与您的输出不同(并显示带有输入参数的静态方法被模拟了。):
staticInput called
dummy
static2 called
2
7
staticInput mock
我仍然相信我提出的版本更好:设置模拟时不会调用真正的静态方法,不幸的是您的代码会发生这种情况。
推荐阅读
- arrays - 如何忽略此问题中的区分大小写?
- mysql - AWS 在通过 mysql 连接后无法看到 RDS mysql DB
- json - 如何将获取请求直接发送到 API?
- templates - 如何减小存储库大小?
- here-api - HERE api反向地理编码器不输出街道号码
- javascript - 积极的前瞻在浏览器的控制台中不起作用,但在 regxr.com 中起作用
- python - 将unicode更改为实际字符?
- python - 散景:所有子图的通用工具,无需固定 x 范围
- vue.js - 在 mapActions() 中找不到 Vuex 模块命名空间
- regex - 在 Spark SQL regexp_replace 中使用 \P{C}