Mockito.anyList() 具有特定值
Mockito.anyList() with specific value
我有一个测试,我模拟了这样的一些服务的结果:
Mockito.when(service.getValuesByIds(Mockito.anyList()))
.thenReturn(values);
我的问题是有没有可能模拟一个包含某些特定值的列表(不关心列表中的其他值,但它们也存在)?
大概是这样的:
Mockito.when(service.getValuesByIds(Mockito.anyList().containing(555)))
.thenReturn(values);
您可以使用 custom argument matchers
@Test
void shouldMatchValue() {
...
ArgumentMatcher<List<Integer>> matcher = new CustomMatcher(555);
Mockito.when(service.getValuesByIds(argThat(matcher)))).thenReturn(values);
...
}
public class CustomMatcher implements ArgumentMatcher<List<Integer>> {
private final int expected;
public CustomMatcher(int expected) {
this.expected = expected;
}
@Override
public boolean matches(List<Integer> myList) {
// put logic here for example,
return myList.contains(expected);
}
}
从 Mockito 2.1.0 和 Java 8 开始,您可以将 lambda 传递给 argThat
,这更接近您的示例 -
when(service).getValuesByIds(argThat(myList -> myList.contains(555)).thenReturn(values);
我有一个测试,我模拟了这样的一些服务的结果:
Mockito.when(service.getValuesByIds(Mockito.anyList()))
.thenReturn(values);
我的问题是有没有可能模拟一个包含某些特定值的列表(不关心列表中的其他值,但它们也存在)?
大概是这样的:
Mockito.when(service.getValuesByIds(Mockito.anyList().containing(555)))
.thenReturn(values);
您可以使用 custom argument matchers
@Test
void shouldMatchValue() {
...
ArgumentMatcher<List<Integer>> matcher = new CustomMatcher(555);
Mockito.when(service.getValuesByIds(argThat(matcher)))).thenReturn(values);
...
}
public class CustomMatcher implements ArgumentMatcher<List<Integer>> {
private final int expected;
public CustomMatcher(int expected) {
this.expected = expected;
}
@Override
public boolean matches(List<Integer> myList) {
// put logic here for example,
return myList.contains(expected);
}
}
从 Mockito 2.1.0 和 Java 8 开始,您可以将 lambda 传递给 argThat
,这更接近您的示例 -
when(service).getValuesByIds(argThat(myList -> myList.contains(555)).thenReturn(values);