gpt4 book ai didi

java - 带输入的 PowerMockito mockStatic

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

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

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

最佳答案

我想出的最干净的代码是明确标记应该转发到其实际实现的方法。

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

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

关于java - 带输入的 PowerMockito mockStatic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207164/

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