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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:33:31  来源:igfitidea点击:

how to verify a method of a non-mock object is called?

javaunit-testingmockito

提问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 anotherObjas a spy you can verify method calls on that object. In your example you need to make sure that the call to foouses 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(...);

回答by CodeHunter

Annotate the non-mock object with @Spyannotation and then check for verify(). Check this

使用注释对非模拟对象进行@Spy注释,然后检查verify(). 检查这个