问题描述
In Mockito documentation and javadocs it says
建议将 ArgumentCaptor 与验证一起使用,但不要与存根一起使用.
但我不明白 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 进行存根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!