Video in progress

Strong Middle 🧪 Testing

When do you need thenAnswer and doAnswer in Mockito? Show an example.

When the answer isn't known in advance and has to be computed from the call's arguments: returning the passed object with an ID, invoking a callback, simulating the side effect of a void method. But if the logic inside an answer grows, it's time to write a fake instead of a mock.

📖 Answer

Three typical cases.

save should return the passed object with an ID:

when(repo.save(any(Order.class))).thenAnswer(inv -> {
    Order o = inv.getArgument(0);
    o.setId(100L);
    return o;
});

If you only need to return the argument, there's a ready-made one: thenAnswer(AdditionalAnswers.returnsFirstArg()).

A void method should call a callback. when(...) doesn't compile with void, so use doAnswer:

doAnswer(inv -> {
    Consumer<SmsResult> callback = inv.getArgument(1);
    callback.accept(SmsResult.delivered());
    return null;
}).when(smsGateway).sendAsync(anyString(), any());

You can also write an answer for a response that depends on the number of calls (errors for the first two, then success), but a plain thenThrow(...).thenThrow(...).thenReturn(...) chain is easier to read.

When to stop: when an if, a Map and a counter show up inside the answer, you're rewriting the dependency. For example, for a repository, instead of piling up "save, then return with findById" logic across answers, a small InMemoryOrderRepository fake on top of a HashMap is cleaner and reusable.