/ TEST, UNIT TEST

Improve your tests with Mockito's capture

Unit Testing mandates to test the unit in isolation. In order to achieve that, the general consensus is to design our classes in a decoupled way using DI. In this paradigm, whether using a framework or not, whether using compile-time or runtime compilation, object instantiation is the responsibility of dedicated factories. In particular, this means the new keyword should be used only in those factories.

Sometimes, however, having a dedicated factory just doesn’t fit. This is the case when injecting an narrow-scope instance into a wider scope instance. A use-case I stumbled upon recently concerns event bus, code like this one:

 public class Sample {
    private EventBus eventBus;

    public Sample(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    public void done() {
        Result result = computeResult()
        eventBus.post(new DoneEvent(result));
    }

    private Result computeResult() {
        ...
    }
}

With a runtime DI framework - such as the Spring framework, and if the DoneEvent had no argument, this could be changed to a lookup method pattern.

public void done() {
    eventBus.post(getDoneEvent());
}

public abstract DoneEvent getDoneEvent();

Unfortunately, the argument just prevents us to use this nifty trick. And it cannot be done with runtime injection anyway. It doesn’t mean the done() method shouldn’t be tested, though. The problem is not only how to assert that when the method is called, a new DoneEvent is posted in the bus, but also check the wrapped result.

Experienced software engineers probably know about the Mockito.any(Class<?>) method. This could be used like this:

public void doneShouldPostDoneEvent() {
    EventBus eventBus = Mockito.mock(EventBus.class);
    Sample sample = new Sample(eventBus);
    sample.done();
    Mockito.verify(eventBus).post(Mockito.any(DoneEvent.class));
}

In this case, we make sure an event of the right kind has been posted to the queue, but we are not sure what the result was. And if the result cannot be asserted, the confidence in the code decreases. Mockito to the rescue. Mockito provides captures, that act like placeholders for parameters. The above code can be changed like this:

public void doneShouldPostDoneEventWithExpectedResult() {
    ArgumentCaptor<DoneEvent> captor = ArgumentCaptor.forClass(DoneEvent.class); (1)
    EventBus eventBus = Mockito.mock(EventBus.class);
    Sample sample = new Sample(eventBus);
    sample.done();
    Mockito.verify(eventBus).post(captor.capture());                             (2)
    DoneEvent event = captor.getCapture();                                       (3)
    assertThat(event.getResult(), is(expectedResult));                           (4)
}
1 We create a new ArgumentCaptor.
2 We replace any() usage with captor.capture() and the trick is done.
3 The result is then captured by Mockito and available through captor.getCapture().
4 Using Hamcrest, makes sure the result is the expected one.
Nicolas Fränkel

Nicolas Fränkel

Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

Read More
Improve your tests with Mockito's capture
Share this