我正在尝试使用Mockito的ArgumentCapture
检索使用的通用参数,但是在我的方法中,使用了相同的基本类型,但两次使用了不同的通用参数。
为了简化示例,我编写了与代码不同但存在相同问题的测试:
@Captor private ArgumentCaptor<ArrayList<String>> stringl;
@Captor private ArgumentCaptor<ArrayList<Boolean>> booleanl;
@Before
public void setup()
{
MockitoAnnotations.initMocks(this);
} //setup
@Test
public void test()
{
Foo foo = mock(Foo.class);
List<String> stringList = new ArrayList<String>();
List<Boolean> booleanList = new ArrayList<Boolean>();
foo.doSomething(stringList);
foo.doSomething(booleanList);
verify(foo).doSomething(stringl.capture());
verify(foo).doSomething(booleanl.capture());
} //test
private static class Foo
{
public <T> void doSomething(List<T> list){}
}
执行测试会产生以下错误:
org.mockito.exceptions.verification.TooManyActualInvocations:
foo.doSomething(<Capturing argument>);
Wanted 1 time:
-> at test(Test.java:19)
But was 2 times. Undesired invocation:
-> at test(Test.java:21)
为了查看发生了什么,我在验证方法中添加了
times(2)
,然后检查了参数捕获。两者都接受了第二次调用,这意味着我永远无法捕获类型为List<String>
的第一个参数。有没有办法让
ArgumentCapture
识别同一基本类型的不同泛型类型,即区分List<Boolean>
和List<String>
?干杯,
阿列克谢蓝
最佳答案
不使用现有的ArgumentCaptor
类。由于类型擦除,此信息丢失。我建议您使用单个捕获器,并在所有调用中传递参数。然后,您可以使用List<String>
验证它是第一次调用,是使用List<Boolean>
来第二次调用它。当然,您可以通过验证列表的内容来做到这一点。