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

时间:2019-05-19 14:35:45

标签: java mockito powermock powermockito

当我尝试使用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

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"));
    }
}

引用Using PowerMock with Mockito: Mocking Static Method