gpt4 book ai didi

java - 模拟时递归调用系统

转载 作者:行者123 更新时间:2023-12-01 14:03:42 24 4
gpt4 key购买 nike

我已经尝试 mock 我的代码有一段时间了。我在 mock 方面还是个新手,所以我还有很多事情要做。我正在使用 Powermockito 与 Mockito 和 Easymock 集成。

我在模拟我想要测试的方法内部的方法时遇到困难。所以这是我面临的情况的示例:

public class trialClass {
public static int try2(){
return 3;
}

public static int try(int a){
return try2() + a;
}
}

我的测试类是:

@RunWith(PowerMockRunner.class)
@PrepareForTest(trial.class)
public class trialTest {

@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(trial.class);

//Here I expect try2() to return 10, even it return 3
PowerMockito.when(trial.try2()).thenReturn(10);
}

@Test
public void testtry() throws Exception {
//After try2() returns 10 recursively inside my try() method,
//I expect result to be 11
Assert.assertEquals(11, trial.try(1));
}
}

我的这个问题实际上来 self 的 session 变量。我的 session 保存一些值,并且 X 方法返回该值。我所需要的只是递归地模拟 X 方法,这个问题只是模拟这种情况。

感谢大家的帮助。

最佳答案

您需要使用Mockito.CALLS_REAL_METHODS

因此在您的测试设置中:

PowerMockito.mockStatic(trial.class, CALLS_REAL_METHODS);

关于java - 模拟时递归调用系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19112482/

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