JMock2 中是否有任何方法可以让测试在执行给定模拟的方法调用时通过? 换句话说,我想编写一些测试代码,例如:
assertTrue(when(aRequestMock).methodCall());
要测试生产代码,例如:
public void methodUnderTest(){
// Some initialization code and members call
request.foo();
String a = anotherInstance.bar();
// many more calls to follow
}
...所以我不需要模拟 'anotherInstance.bar()'
返回值以及任何其他模拟调用?
我知道它并不代表任何严格的检查,也不能被视为最佳实践,但在使用一长串成员方法测试方法时它会很方便。
最佳答案
给定代码:
public void methodUnderTest(){
request.foo();
anInstance.bar();
yetAnotherInstance.baz();
}
一旦调用foo()
,就无法跳过bar()
和baz()
的执行。我还要说你不想这样做,因为即使你可以在测试中跳过它,它无论如何都会在生产中执行,所以你最好也测试它:-)
你能做的最近的事情是
context.checking(new Expectations() {{
oneOf(requestMock).foo();
ignoring(anInstanceMock).bar();
ignoring(yetAnotherInstanceMock).baz();
}});
这里我在第一行使用 oneOf()
,因为 foo()
是测试的焦点。您还可以通过不提及 bar()
和 baz()
来简化此操作:
context.checking(new Expectations() {{
oneOf(requestMock).foo();
ignoring(anInstanceMock);
ignoring(yetAnotherInstanceMock);
}});
但是,请记住,这样做您将忽略 anInstanceMock
和 yetAnotherInstanceMock
上的任何方法调用。
关于java - 让测试通过一组 JMock 的模拟方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54150528/