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

查看:31
本文介绍了如何使用 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?

推荐答案

假设以下方法进行测试:

Assuming the following method to test:

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天全站免登陆