mockito给定大小的anyList [英] mockito anyList of a given size

查看:1501
本文介绍了mockito给定大小的anyList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mockito验证是否已调用某个方法。方法:

  public void createButtons(final List< Button> buttonsConfiguration){...} 

由于传递哪个列表并不重要,我验证方法是如下调用的:

  verify(mock).createButtons(Matchers.anyListOf(Button.class)); 

但是, List 的大小是重要。因此,哪个 List 并不重要,但列表必须有X个元素。



这是可能的吗?所有?

解决方案

一种方法是使用Captor

  ArgumentCaptor<列表> captor = ArgumentCaptor.forClass(List.class); 
verify(mock).createButtons(captor.capture());
assertEquals(x,captor.getValue()。size()); //或者如果期望多个列表:
assertEquals(x,captor.getValues()。size());

参见http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#15 了解文档。



您还可以使用自定义参数匹配器。文档显示了一个完全符合您要求的示例:



http://docs.mockito.googlecode.com/hg/org/mockito/ArgumentMatcher.html

  class IsListOfTwoElements扩展ArgumentMatcher< List> {
public boolean matches(Object list){
return((List)list).size()== 2;
}
}

List mock = mock(List.class);
when(mock.addAll(argThat(new IsListOfTwoElements())))。thenReturn(true);
mock.addAll(Arrays.asList(one,two));
verify(mock).addAll(argThat(new IsListOfTwoElements()));

例如,您可以添加构造函数,以便指定所需的列表大小等。 / p>

I'm verifying with mockito that a method has been called. The method:

public void createButtons(final List<Button> buttonsConfiguration) {...}

Since It doesn't matter which list is passed I verify that the method is called as follows:

verify(mock).createButtons(Matchers.anyListOf(Button.class));

But, the size of the List is important. So, it doesn't matter which List but the list has to have X elements.

Is that possible at all?

解决方案

One way is to use a Captor

ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
verify(mock).createButtons(captor.capture());
assertEquals(x, captor.getValue().size()); // or if expecting multiple lists:
assertEquals(x, captor.getValues().size());

See http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#15 for the documentation.

You could also use a custom argument matcher. The documentation shows an example that does exactly what you want:

http://docs.mockito.googlecode.com/hg/org/mockito/ArgumentMatcher.html

 class IsListOfTwoElements extends ArgumentMatcher<List> {
     public boolean matches(Object list) {
         return ((List) list).size() == 2;
     }
 }

 List mock = mock(List.class);
 when(mock.addAll(argThat(new IsListOfTwoElements()))).thenReturn(true);
 mock.addAll(Arrays.asList("one", "two"));
 verify(mock).addAll(argThat(new IsListOfTwoElements()));

You could, for instance, also add a constructor so you can specify list size desired, etc.

这篇关于mockito给定大小的anyList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆