如何验证非模拟对象的方法? [英] how to verify a method of a non-mock object is called?

查看:96
本文介绍了如何验证非模拟对象的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎mockito只验证是否调用了模拟对象的方法,并且模拟对象总是具有某些功能。比如doReturn()。when(模拟对象)...

It seems mockito only verify whether a method of a mock object is called and the mock object always have sth. like doReturn().when(mock object)...

但是我可以创建一个模拟对象并定义doReturn()。when(模拟对象)..
然后验证另一个对象的方法被调用?

But can I creat a mock object and define doReturn().when(mock object).. and then verify a method of another object is called?

这是我想要做的:我定义了一个mockEnvironment并返回一个响应,无论发生什么。但后来我想验证在不同情况下调用anotherObj的不同方法。

Here is what I want to do: I define a mockEnvironment and return a response no matter what happen. But then I want to verify different methods of anotherObj is called in different cases.

怎么做?

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(...);
}


推荐答案

你可以使用Mockito < a href =http://static.javadoc.io/org.mockito/mockito-core/2.2.29/org/mockito/Mockito.html#13 =noreferrer>间谍。如果您将 anotherObj 设置为间谍,则可以验证该对象上的方法调用。在您的示例中,您需要确保对 foo 的调用使用spy而不是 anotherObj 的普通实现。间谍设置如下:

You can use a Mockito Spy for 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:

AnotherClass anotherObjSpy = Mockito.spy(new AnotherClass());
// do stuff
verify(anotherObjSpy).codePath1(...);

这篇关于如何验证非模拟对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆