首页 > 解决方案 > PowerMockito mockStatic 带输入

问题描述

我需要模拟一个具有输入参数的静态方法。对于类中的其他函数,必须调用原始方法,而对于我试图模拟的函数,必须执行模拟的存根。我尝试了以下代码,但它没有按预期工作。

public class Foo {
    public static String static1() {
        System.out.println("static1 called");
        return "1";
    }

    public static String static2() {
        System.out.println("static2 called");
        return "2";
    }

    public static String staticInput(int i) {
        System.out.println("staticInput called");
        return "static " + i;
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class })
public class TestMockito {

    @Test
    public void test() throws Exception {

        PowerMockito.mockStatic(Foo.class, Mockito.CALLS_REAL_METHODS);
        PowerMockito.doReturn("dummy").when(Foo.class ,"static1");

        PowerMockito.when(Foo.staticInput(anyInt())).thenAnswer(invocation -> {
            System.out.println((int)invocation.getArgument(0));
            return "staticInput mock";
        });


        //        PowerMockito.doAnswer(new Answer() {
        //            @Override
        //            public Object answer(InvocationOnMock invocation) throws Throwable {
        //                int i = (int) invocation.getArguments()[0];
        //                System.out.println(i);
        //                return i;
        //            }
        //
        //        }).when(Foo.staticInput(anyInt()));

        System.out.println(Foo.static1());
        System.out.println(Foo.static2());
        System.out.println(Foo.staticInput(7));
    }
}

我得到以下输出:

staticInput called  
dummy 
static2 called  
2 
staticInput called  
static 7

标签: javajunitmockitopowermockpowermockito

解决方案


我想出的最简洁的代码是明确地标记应该转发到它们实际实现的方法。

PowerMockito.mockStatic(Foo.class);
PowerMockito.doReturn("dummy").when(Foo.class, "static1");
PowerMockito.when(Foo.static2()).thenCallRealMethod();
PowerMockito.when(Foo.staticInput(anyInt())).thenAnswer(invocation -> {
    System.out.println((int)invocation.getArgument(0));
    return "staticInput mock";
});

输出(符合我的期望):

dummy
static2 called
2
7
staticInput mock

奇怪的是,我的原始代码输出与您的输出不同(并显示带有输入参数的静态方法被模拟了。):

staticInput called
dummy
static2 called
2
7
staticInput mock

我仍然相信我提出的版本更好:设置模拟时不会调用真正的静态方法,不幸的是您的代码会发生这种情况。


推荐阅读