問題描述
我正在使用 mockito 驗證一個方法已被調用.方法:
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));
但是,List
的大小很重要.因此,哪個 List
并不重要,但列表必須有 X 個元素.
But, the size of the List
is important. So, it doesn't matter which List
but the list has to have X elements.
這可能嗎?
推薦答案
一種方法是使用 Captor
One way is to use a Captor
ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
verify(mock).createButtons(captor.capture());
assertEquals(x, captor.getValue().size()); // if expecting single list
assertEquals(x, captor.getValues().size()); // if expecting multiple lists
請參閱 http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#15 獲取文檔.
您還可以使用自定義參數匹配器.該文檔顯示了一個完全符合您要求的示例:
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 給定大小的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!