首页 > 解决方案 > 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 打印:

staticInput 称为
静态 1

标签: javamockitopowermockpowermockito

解决方案


您可以稍微改变方法并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:模拟静态方法


推荐阅读