cat*_*dog 7 java methods count mockito
我在使用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++;
}
}
Run Code Online (Sandbox Code Playgroud)
和测试类:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
有这样的例外:
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)
Run Code Online (Sandbox Code Playgroud)
请任何想法.提前致谢!
Gar*_*all 10
这会奏效.使用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++;
}
}
Run Code Online (Sandbox Code Playgroud)
这表明您需要进行一些重构以改进您的设计.单个类应该是完全可测试的,而不需要模拟它的部分.无论你认为需要被嘲笑的任何作品都应该被提取到一个或多个合作对象中.不要陷入局部嘲笑的陷阱.听听测试告诉你的内容.你未来的自我会感谢你.