如何使用 ArgumentCaptor 进行存根?

2022-08-31 07:04:29

在Mockito文档javadocs中,它说

建议使用带有验证的 ArgumentCaptor,但不要使用存根。

但我不明白ArgumentCaptor如何用于存根。有人可以解释上面的陈述,并展示ArgumentCaptor如何用于存根或提供一个链接来说明如何做到这一点吗?


答案 1

假设采用以下方法进行测试:

public boolean doSomething(SomeClass arg);

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

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

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

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

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

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

答案 2

假设,如果搜索让你遇到这个问题,那么你可能想要这个:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

为什么?因为像我一样,你重视时间,你不会仅仅为了单个测试场景而实现。.equals

99% 的测试会因 Mock 返回 null 而分崩离析,在合理的设计中,您将不惜一切代价避免返回,使用或迁移到 Kotlin。这意味着不需要经常使用,ArgumentCaptors太乏味而无法编写。nullOptionalverify


推荐