mockito anyList of a given size

后端 未结 4 462
囚心锁ツ
囚心锁ツ 2021-01-01 08:53

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

public void createButtons(final List
4条回答
  •  心在旅途
    2021-01-01 08:57

    One way is to use a Captor

    ArgumentCaptor 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 {
         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.

提交回复
热议问题