问题描述
在Mockito 和它说
In Mockito documentation and javadocs it says
但我不明白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进行存根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!