我需要模拟具有输入参数的静态方法。对于课堂中的其他功能,必须调用原始方法,对于我要模拟的功能,只能执行模拟的存根。我尝试了以下代码,但无法正常工作。
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
我想出的最清洁代码是要明确标记将shoud转发到其真实实现的方法。
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
我仍然相信我提出的版本更好:设置模拟时未调用真正的静态方法,不幸的是您的代码发生。