gpt4 book ai didi

java - Powermockito 模拟静态方法匹配器不起作用

转载 作者:行者123 更新时间:2023-12-02 05:29:26 30 4
gpt4 key购买 nike

当我尝试使用字符串输入模拟静态方法时,当我给出特定字符串时,模拟 stub 就会被执行,但是当我使用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"));
}
}

测试1打印:

dummyStaticStub

测试2打印:

staticInput called
static 1

最佳答案

您可以稍微改变一下方法并使用 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"));
}
}

引用Using PowerMock with Mockito: Mocking Static Method

关于java - Powermockito 模拟静态方法匹配器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56208818/

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