Java Mockito:验证参数而不必强制转换它

Java Mockito:验证参数而不必强制转换它,java,junit,mockito,junit4,hamcrest,Java,Junit,Mockito,Junit4,Hamcrest,我有一个具有以下方法的服务类: void doSomething(List<String> list) void doSomething(列表) 我模拟这个类,我想验证作为参数传递的列表是否只有一个元素。我是这样做的: verify(myService).doSomething((List<String>) argThat(hasSize(1)))) verify(myService).doSomething((列表)argThat(hasSize(1))) 如您

我有一个具有以下方法的服务类:

void doSomething(List<String> list)
void doSomething(列表)
我模拟这个类,我想验证作为参数传递的列表是否只有一个元素。我是这样做的:

verify(myService).doSomething((List<String>) argThat(hasSize(1))))
verify(myService).doSomething((列表)argThat(hasSize(1)))
如您所见,我必须将参数强制转换为
列表
,否则无法编译:

incompatible types: inferred type does not conform to upper bound(s)
  inferred: java.util.Collection<? extends java.lang.Object>
  upper bound(s): java.util.List<java.lang.String>,java.lang.Object
不兼容类型:推断的类型不符合上限

推断:java.util.Collection我更喜欢这个解决方案:

final ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);

verify(myService).doSomething(argumentCaptor.capture());

assertThat(argumentCaptor.getValue().size()).isEqualTo(1);
final ArgumentCaptor ArgumentCaptor=ArgumentCaptor.forClass(List.class);
验证(myService).doSomething(argumentCaptor.capture());
断言(argumentCaptor.getValue().size()).isEqualTo(1);

谢谢。成功了。我不得不重新编写你的代码,因为你发布它的方式没有得到编译-它需要
ArgumentCaptor
,我必须这样做:。如果没有更好的答案,我以后会接受你的答案。虽然它可以工作,但仍然相当复杂,使用匹配器组合的代码会更短更清晰。