gpt4 book ai didi

java - 计算间接方法调用 Mockito

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:20 25 4
gpt4 key购买 nike

我在使用 Mockito 计算方法调用时遇到问题。问题是我想计算调用次数的方法是由其他方法在测试类中间接调用的。这是代码:

public class ClassForTest {
private Integer value;

public void doSmth() {
prepareValue("First call");
prepareValue("Second call");
prepareValue("Third call");
System.out.println(value);
}

protected void prepareValue(String msg) {
System.out.println("This is message: " + msg);
value++;
}
}

和测试类:

public class ClassForTestTest extends TestCase {
@Test
public void testDoSmth() {
ClassForTest testMock = mock(ClassForTest.class);
doNothing().when(testMock).prepareValue(anyString());
testMock.doSmth();
verify(testMock, times(3)).prepareValue(anyString());
}
}

有这样的异常:

Wanted but not invoked:
classForTest.prepareValue(<any>);
-> at org.testing.ClassForTestTest.testDoSmth(ClassForTestTest.java:24)

However, there were other interactions with this mock:
-> at org.testing.ClassForTestTest.testDoSmth(ClassForTestTest.java:21)

请有任何想法。提前致谢!

最佳答案

这会起作用。使用 spy 调用底层方法。确保首先初始化 value

    @Test
public void testDoSmth() {
ClassForTest testMock = spy(new ClassForTest());
testMock.doSmth();
verify(testMock, times(3)).prepareValue(anyString());
}

public class ClassForTest {
private Integer value = 0;

public void doSmth() {
prepareValue("First call");
prepareValue("Second call");
prepareValue("Third call");
System.out.println(value);
}

protected void prepareValue(String msg) {
System.out.println("This is message: " + msg);
value++;
}
}

关于java - 计算间接方法调用 Mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7829659/

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