Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
264 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...