PowerMockito模拟静态方法匹配器不起作用



当我试图用字符串输入模拟静态方法时,当我给出特定的字符串时,模拟的存根将被执行,但是当我使用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打印:

称为
的静态图 静态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"));
    }
}

使用PowerMock与Mockito:Mocking静态方法

参考

相关内容

  • 没有找到相关文章

最新更新