我在计算Mockito的方法调用时遇到了问题。问题是,调用我想要计数的方法在test类中被其他方法间接调用。代码如下:
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)有什么想法请告诉我。提前感谢!
发布于 2011-10-20 10:39:30
这将会起作用。使用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++;
}
}发布于 2011-10-20 11:33:28
这表明你需要一些重构来改进你的设计。一个单独的类应该是完全可测试的,而不需要模拟它的各个部分。您认为需要模拟的任何部分都应该提取到一个或多个协作对象中。‘t落入部分模仿的陷阱。听一听测试告诉你什么。你未来的自己会感谢你的。
发布于 2011-10-20 09:47:17
你在嘲笑被测试的类。Mocking用于测试类的依赖项,而不是类本身。
我怀疑你想要的是Mockito.spy()。然而,这是Mockito Javadoc建议反对的部分模拟。
https://stackoverflow.com/questions/7829659
复制相似问题