1. Introduction

In this short tutorial, we’ll look at lazy verifications in Mockito.

Instead of failing-fast, Mockito allows us to see all results collected and reported at the end of a test.

2. Maven Dependencies

Let’s start by adding the Mockito dependency:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.21.0</version>
</dependency>

3. Lazy Verification

The default behavior of Mockito is to stop at the first failure i.e. eagerly – the approach is also known as fail-fast.

Sometimes we might need to execute and report all verifications – regardless of previous failures.

VerificationCollector is a JUnit rule which collects all verifications in test methods.

They’re executed and reported at the end of the test if there are failures:

public class LazyVerificationTest {
 
    @Rule
    public VerificationCollector verificationCollector = MockitoJUnit.collector();

    // ...
}

Let’s add a simple test:

@Test
public void testLazyVerification() throws Exception {
    List mockList = mock(ArrayList.class);
    
    verify(mockList).add("one");
    verify(mockList).clear();
}

When this test is executed, failures of both verifications will be reported:

org.mockito.exceptions.base.MockitoAssertionError: There were multiple verification failures:
1. Wanted but not invoked:
arrayList.add("one");
-> at com.baeldung.mockito.java8.LazyVerificationTest.testLazyVerification(LazyVerificationTest.java:21)
Actually, there were zero interactions with this mock.

2. Wanted but not invoked:
arrayList.clear();
-> at com.baeldung.mockito.java8.LazyVerificationTest.testLazyVerification(LazyVerificationTest.java:22)
Actually, there were zero interactions with this mock.

Without VerificationCollector rule, only the first verification gets reported:

Wanted but not invoked:
arrayList.add("one");
-> at com.baeldung.mockito.java8.LazyVerificationTest.testLazyVerification(LazyVerificationTest.java:19)
Actually, there were zero interactions with this mock.

4. Conclusion

We had a quick look at how we can use lazy verification in Mockito.

Also, as always, code samples can be found over on GitHub.