gpt4 book ai didi

java - Spy对象值不随when改变,thenReturn

转载 作者:行者123 更新时间:2023-11-30 05:51:13 26 4
gpt4 key购买 nike

public class MainClass {
public void method1() {
…….
String str = getMethod2();
method3(str);
}

protected String getMethod2() {
String str = “Actual Value”
return str;
}
private void method3(String strparam) {
……
}
}

@RunWith(MockitoJunitRunner.class)
public class Testclass {
@InjectMocks
MainClass obj = new MainClass();

……
@Test
public void testSpy() {
MainClass spyMain = spy(obj);
when(spyMain.getMethod2()).thenReturn(new String("Testing spy"));

obj.method1();
……..
}
}

想要使用测试中 getMethod2() 返回的新值,因为它将传递给 method3。我的印象是,从测试类对 method1 的调用调用了 method2,并且我认为从 method2 返回的值是“测试 spy ”,但实际上是“实际值”,并且在运行测试类时“实际值”被传递给 method3。如何使用测试类中的新值?

最佳答案

您正在 obj (obj.method1();) 上调用该方法,而不是在您监视的对象上调用该方法:spyMain.method1 ();.

关于java - Spy对象值不随when改变,thenReturn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53887790/

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