Mockito ArgumentMatcher验证某个集合中是否包含arg值

h43kikqp  于 2022-11-29  发布在  其他
关注(0)|答案(2)|浏览(103)

有没有办法,使用Mockito来定义这样的表达式?

when(mockObject.getValuesFor(in(1, 2, 3)).thenReturn(List.of(...)));

ArgumentMatchersAdditionalMatchers中定义的方法中,我找不到像in()这样的方法,所以我想知道哪种方法是实现我所需要的方法的常用方法。

    • 注意**我所模拟的方法声明如下:
List<Integer> getValuesFor(int arg) {...}
kcugc4gi

kcugc4gi1#

我认为intThat非常接近您的需求:

when(mockObject.getValuesFor(intThat(x -> Set.of(1, 2, 3).contains(x))))
  .thenReturn(List.of(3, 4, 5));

此外,您可以提取一个生成内部ArgumentMatcher<Integer>的方法,这将使您的代码看起来像

when(mockObject.getValuesFor(intThat(isOneOf(1, 2, 3))))
  .thenReturn(List.of(3, 4, 5));
72qzrwbm

72qzrwbm2#

我找不到。所以我使用下面的解决方法。

List list = List.of(1, 2, 3);
when(mockObject.getValuesFor(list).thenReturn(List.of(...)));

//do actual test method call

ArgumentCaptor<List> listCaptor = ArgumentCaptor.class(List.class);
verify(mockObject).getValuesFor(listCaptor.capture());

assertEquals(3, list.getValue().size());
assertEquals(1, list.getValue().get(0));
assertEquals(2, list.getValue().get(1));
assertEquals(3, list.getValue().get(2));

如果没有传递相同的列表作为方法参数,则测试用例在assert语句中将失败。

相关问题