如何使用ArgumentCaptor进行存根? [英] How to use ArgumentCaptor for stubbing?

查看:106
本文介绍了如何使用ArgumentCaptor进行存根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Mockito 文档 javadocs 它说

In Mockito documentation and javadocs it says


建议使用ArgumentCaptor进行验证但不使用存根。

It is recommended to use ArgumentCaptor with verification but not with stubbing.

但我不明白ArgumentCaptor如何用于存根。有人可以解释上面的陈述并说明如何使用ArgumentCaptor进行存根或提供一个显示如何完成的链接吗?

but I don't understand how ArgumentCaptor can be used for stubbing. Can someone explain the above statement and show how ArgumentCaptor can be used for stubbing or provide a link that shows how it can be done?

推荐答案

假设要测试以下方法:

public boolean doSomething(SomeClass arg);

Mockito文档说你应该以这种方式使用captor:

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

因为您可以在存根期间使用匹配器:

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

但验证是另一回事。如果您的测试需要确保使用特定参数调用此方法,请使用 ArgumentCaptor ,这就是设计它的情况:

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

这篇关于如何使用ArgumentCaptor进行存根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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