如何模拟影响对象的void返回方法 [英] How to mock a void return method affecting an object

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

问题描述

我正在为我的应用程序编写单元测试,我想知道Mockito框架是否有可能影响传递到不返回模拟类的方法中的对象.例如,调用一个包含方法的模拟验证类,该方法返回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.

如果您只想测试与模拟对象的交互,则只需使用

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

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

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