Search code examples
mockitoassertionverifyerrorcollector

How to use soft assertions in Mockito?


I know that we can use ErrorCollector or soft assertions (AssertJ or TestNG) that do not fail a unit test immediately.

How they can be used with Mockito assertions? Or if they can't, does Mockito provide any alternatives?


Code sample

verify(mock).isMethod1();
verify(mock, times(1)).callMethod2(any(StringBuilder.class));
verify(mock, never()).callMethod3(any(StringBuilder.class));
verify(mock, never()).callMethod4(any(String.class));

Problem

In this snippet of code if a verification will fail, then the test will fail which will abort the remaining verify statements (it may require multiple test runs until all the failures from this unit test are revealed, which is time-consuming).


Solution

  • Since Mockito 2.1.0 you can use VerificationCollector rule in order to collect multiple verification failures and report at once.

    Example

    import static org.mockito.Mockito.verify;
    import org.junit.Rule;
    import org.mockito.junit.MockitoJUnit;
    import org.mockito.junit.VerificationCollector;
    
    // ...
    
        @Rule
        public final VerificationCollector collector = MockitoJUnit.collector();
    
    
        @Test
        public void givenXWhenYThenZ() throws Exception {
            // ...
            verify(mock).isMethod1();
            verify(mock, times(1)).callMethod2(any(StringBuilder.class));
            verify(mock, never()).callMethod3(any(StringBuilder.class));
            verify(mock, never()).callMethod4(any(String.class));
        }
    

    Known issues

    This rule cannot be used with ErrorCollector rule in the same test method. In separate tests it works fine.