Java 如何验证非模拟对象的方法被调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31039283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to verify a method of a non-mock object is called?
提问by user389955
It seems mockito only verifies whether a method of a mock object is called and the mock object always have something like doReturn().when(mock object)
似乎 mockito 只验证是否调用了模拟对象的方法,并且模拟对象总是有类似的东西 doReturn().when(mock object)
But can I create a mock object and define doReturn().when(mock object)
and then verify a method of another object is called?
但是我可以创建一个模拟对象并定义doReturn().when(mock object)
然后验证另一个对象的方法被调用吗?
Here is what I want to do: I define a mockEnvironment and return a response no matter what happens. But then I want to verify different methods of anotherObj is called in different cases.
这是我想要做的:我定义一个模拟环境并无论发生什么都返回一个响应。但是后来我想验证在不同情况下调用 anotherObj 的不同方法。
How to do that?
怎么做?
public class BaseClass {
private Environment mockEnvironment;
@Test
public void testcase () {
setMockitoEnvironment();
response = foo(mockEnvironment, argument1);
verify(anotherObj).codePath1(...);
response = foo(mockEnvironment, argument2);
verify(anotherObj).codePath2(...);
}
}
//this method successfully return a response with any input
//because I do not care how response is eventually generated,
//I only care whether code path reaches createResponse() via
//code path 1 or code path 2.
private void setMockitoEnvironment() {
mockEnvironment = mock(Environment.class);
doReturn (response).when(mockEnvironment).createResponse(for any input);
}
private Response foo(...) {
...
return createResponse(...);
}
采纳答案by K Erlandsson
You can use a Mockito Spyfor this. If you setup anotherObj
as a spy you can verify method calls on that object. In your example you need to make sure that the call to foo
uses the spy instead of an ordinary implementation of anotherObj
. The spy is setup something like this:
您可以为此使用 Mockito Spy。如果您设置anotherObj
为间谍,您可以验证对该对象的方法调用。在您的示例中,您需要确保调用foo
使用 spy 而不是anotherObj
. 间谍的设置是这样的:
AnotherClass anotherObjSpy = Mockito.spy(new AnotherClass());
// do stuff -- e.g. anotherObjSpy.foo(...);
verify(anotherObjSpy).codePath1(...);