更新时间:2022-04-24 19:12:59
你有几个选择:
在 SampleObj
上实现 equals
和 hashCode
.因为您没有将 fooList
包装在匹配器中,所以 Mockito 使用 List.equals
进行检查,后者检查 equals
以查找每个 List 中的相应对象.Object.equals 的默认行为是 a.equals(b)
iff a == b
——也就是说,当对象引用同一个实例时,它们是相等的——- 但如果每个 SampleObj("foobar") 都等于其他所有 SampleObj("foobar"),则欢迎您覆盖它.
Implement equals
and hashCode
on SampleObj
. Because you didn't wrap fooList
in a matcher, Mockito checks with List.equals
, which checks equals
for corresponding objects in each List. The default behavior of Object.equals is that a.equals(b)
iff a == b
--that is, objects are equal iff they refer to the same instance--but you're welcome to override that if every SampleObj("foobar") equals every other SampleObj("foobar").
使用您编写的 Hamcrest Matcher.
Use a Hamcrest Matcher you write.
private static Matcher<List<SampleObj>> isAListWithObjs(String... strings) {
return new AbstractMatcher<List<SampleObj>>() {
@Override public boolean matches(Object object) {
// return true if object is a list of SampleObj corresponding to strings
}
};
}
// in your test
verify(mockedAnotherService).method2(argThat(isAnObjListWith("another param")));
请注意,您也可以只制作单个 SampleObj 的 Matcher,然后使用像 hasItem
这样的 Hamcrest 包装器.在此处查看更多匹配器.
Note that you could also just make a Matcher of a single SampleObj, and then use a Hamcrest wrapper like hasItem
. See more matchers here.
使用 Captor 以您自己的方式检查 equals
:
Use a Captor to check equals
your own way:
public class YourTest {
// Populated with MockitoAnnotations.initMocks(this).
// You can also use ArgumentCaptor.forClass(...), but with generics trouble.
@Captor ArgumentCaptor<List<SampleObj>> sampleObjListCaptor;
@Test public void testMethod1() {
// ...
verify(mockedAnotherService).method2(sampleObjListCaptor.capture());
List<SampleObj> sampleObjList = sampleObjListCaptor.getValue();
assertEquals(1, sampleObjList.size());
assertEquals("another param", sampleObjList.get(0).getTitle());
}