如何模拟影响对象的无效返回方法
我正在为我的应用程序编写单元测试,我想知道 Mockito 框架是否有可能影响传递给返回模拟类的 void 方法的对象.例如,调用一个模拟验证类,该类包含一个返回 void 但通过作为参数传入的对象跟踪各种更改和元数据的方法..
I am writing unit tests for my application and I was wondering if it is possible for the Mockito framework to affect an object that is passed into a method that returns void of a mocked class. For instance, calling a mocked validation class that contains a method that returns void but tracks various changes and metadata via an object passed in as an argument. .
public GetCartItemsOutput getCartItems(GetCartItemsInput getCartItemsInput) {
CartItemsFilter cartItemsFilter = new CartItemsFilter();
validator.validateCartItemsInput(getCartItemsInput, cartItemsFilter); ...
我为我的其他测试模拟了验证器类,但对于这个我需要模拟对 cartItemsFilter 对象的更改,我不知道该怎么做.
I mocked the validator class for my other tests but for this one I need mock the changes to the cartItemsFilter object which I do not know how to do.
推荐答案
答案是肯定的,你可以,而且基本上有两个级别,根据你的测试需要.
The answer is yes, you can, and there are basically two levels of doing this, based on the need of your test.
如果您只想测试与模拟对象的交互,您可以简单地使用 verify()
方法,验证是否调用了 void 方法.
If you merely want to test the interaction with the mocked object, you can simply use the verify()
method, to verify that the void method was called.
如果您的测试确实需要模拟对象来修改传递给它的参数,您将需要实现 答案
:
If your test genuinely needs the mocked object to modify parameters passed to it, you will need to implement an Answer
:
EDITED 显示使用 void 方法的正确形式
EDITED to show proper form of using Answer with void method
doAnswer(new Answer() {
@Override
Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
return null; // void method, so return null
}
}).when(mock).someMethod();
在 Java 8+ 中,上面的内容使用 lambda 进行了简化:
In Java 8+, the above is simplified with a lambda:
doAnswer(invocation-> {
Object[] args = invocation.getArguments();
((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
return null;
}).when(mock).someMethod();
相关文章