Ignores stubbed methods of given mocks for the sake of verification.
Sometimes useful when coupled with
verifyNoMoreInteractions()
or verification
inOrder()
.
Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
Warning, ignoreStubs()
might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...));
Bear in mind that Mockito does not recommend bombarding every test with verifyNoMoreInteractions()
for the reasons outlined in javadoc for
Mockito#verifyNoMoreInteractions(Object...)Other words: all *stubbed* methods of given mocks are marked *verified* so that they don't get in a way during verifyNoMoreInteractions().
This method changes the input mocks! This method returns input mocks just for convenience.
Ignored stubs will also be ignored for verification inOrder, including
org.mockito.InOrder#verifyNoMoreInteractions().
See the second example.
Example:
//mocking lists for the sake of the example (if you mock List in real you will burn in hell)
List mock1 = mock(List.class), mock2 = mock(List.class);
//stubbing mocks:
when(mock1.get(0)).thenReturn(10);
when(mock2.get(0)).thenReturn(20);
//using mocks by calling stubbed get(0) methods:
System.out.println(mock1.get(0)); //prints 10
System.out.println(mock2.get(0)); //prints 20
//using mocks by calling clear() methods:
mock1.clear();
mock2.clear();
//verification:
verify(mock1).clear();
verify(mock2).clear();
//verifyNoMoreInteractions() fails because get() methods were not accounted for.
try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);
//However, if we ignore stubbed methods then we can verifyNoMoreInteractions()
verifyNoMoreInteractions(ignoreStubs(mock1, mock2));
//Remember that ignoreStubs() *changes* the input mocks and returns them for convenience.
Ignoring stubs can be used with
verification in order:
List list = mock(List.class);
when(mock.get(0)).thenReturn("foo");
list.add(0);
System.out.println(list.get(0)); //we don't want to verify this
list.clear();
InOrder inOrder = inOrder(ignoreStubs(list));
inOrder.verify(list).add(0);
inOrder.verify(list).clear();
inOrder.verifyNoMoreInteractions();