当我尝试使用String输入模拟静态方法时,当我提供特定的String时,将执行模拟存根,但是当我使用anyString()时,它将无法按预期运行。
public class Foo {
public static String staticInput(String s) {
System.out.println("staticInput called");
return "static " + s;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class})
public class TestMockito {
@Test
public void test1() throws Exception {
PowerMockito.spy(Foo.class);
PowerMockito.doReturn("dummyStaticStub").when(Foo.class, "staticInput", "1");
System.out.println(Foo.staticInput("1"));
}
@Test
public void test2() throws Exception {
PowerMockito.spy(Foo.class);
PowerMockito.doReturn("dummyStaticIn").when(Foo.class, "staticInput", anyString());
System.out.println(Foo.staticInput("1"));
}
}
test1打印:
dummyStaticStub
test2打印:
staticInput已调用
静态1
答案 0 :(得分:0)
您可以稍微改变一下方法,而改为使用PowerMockito.mockStatic
@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class})
public class TestMockito {
@Test
public void test1() throws Exception {
PowerMockito.mockStatic(Foo.class);
Mockito.when(Foo.staticInput("1")).thenReturn("dummyStaticStub");
System.out.println(Foo.staticInput("1"));
}
@Test
public void test2() throws Exception {
PowerMockito.mockStatic(Foo.class);
PowerMockito.when(Foo.staticInput(anyString())).thenReturn("dummyStaticIn");
System.out.println(Foo.staticInput("1"));
}
}