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?
We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.
What are Matchers? Matchers are like regex or wildcards where instead of a specific input (and or output), you specify a range/type of input/output based on which stubs/spies can be rest and calls to stubs can be verified. All the Mockito matchers are a part of 'Mockito' static class.
Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo. class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.
Mockito Argument Matcher - eq() When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With