skip to content

Mockito ships an AdditionalAnswers utility class alongside hand-written Answer lambdas. Which helpers does it provide, and when would you use them instead of writing the lambda yourself?

level: middleimportance: should knowfreq 30%

answer

  1. returnsFirstArg / returnsLastArg / returnsArgAt
  2. returnsElementsOf(collection)
  3. delegatesTo(realImpl) - separate object, still verifiable
  4. answersWithDelay(ms, answer) sleeps the caller
  5. AdditionalAnswers.answer((a, b) -> ...) typed lambdas

basics

~10 s

AdditionalAnswers offers ready-made answers: returnsFirstArg / returnsSecondArg / returnsLastArg to echo an argument, returnsElementsOf(collection) to walk a list, delegatesTo(realObject) to forward calls to a real implementation, and answersWithDelay(millis, answer) to simulate latency.

solid answer

~50 s

`org.mockito.AdditionalAnswers` is a static factory of common `Answer` implementations, used as `thenAnswer(returnsFirstArg())`. - **returnsFirstArg() / returnsSecondArg() / returnsLastArg()** - echo an argument. The idiomatic way to stub `save(entity)` returning the entity, and clearer than a lambda with a magic index. - **returnsElementsOf(Collection)** - hand back the collection's elements one per call; useful when the sequence is computed rather than literal. - **delegatesTo(Object)** - forward every unstubbed call to a real object with a compatible signature. Handy when you want real behaviour but still want to `verify()` interactions, or to back a mocked interface with a hand-written in-memory implementation. - **answersWithDelay(long millis, Answer)** - sleep on the calling thread, then delegate. Used to exercise timeout, retry, or slow-dependency paths. Prefer them for readability; drop back to a lambda when the logic is genuinely bespoke. Delay answers add real wall-clock time, so keep them to a few tests and short delays.

code

java · 8 lines
java
import static org.mockito.AdditionalAnswers.*;

when(repo.save(any(User.class))).thenAnswer(returnsFirstArg());
when(idGen.next()).thenAnswer(returnsElementsOf(List.of(1L, 2L, 3L)));
when(slowClient.call()).thenAnswer(answersWithDelay(200, inv -> "late"));

RatesApi realRates = new InMemoryRatesApi();
RatesApi mockRates = mock(RatesApi.class, withSettings().defaultAnswer(delegatesTo(realRates)));

go deeper

for a junior

Know that returnsFirstArg() exists and is the neat way to stub a save() that echoes its argument.

for a middle

List the main helpers with a use case each and explain why a named helper reads better than an indexed lambda.

for a senior

Discuss delegatesTo versus spy for partial-real collaborators, and treat answersWithDelay as a flakiness risk to be budgeted.

for a principal

Weigh helper-based mocks against hand-written fakes for a whole suite: which one keeps intent visible and which one quietly encodes a second implementation.

## Why a helper class exists A handful of `Answer` shapes come up in nearly every codebase. Rather than have everyone rewrite `inv -> inv.getArgument(0)`, Mockito collects them as static factories on `org.mockito.AdditionalAnswers`. They are ordinary `Answer` objects, so they plug into `thenAnswer(...)` (or `willAnswer(...)` in BDD style) exactly like a lambda. ```java import static org.mockito.AdditionalAnswers.returnsFirstArg; when(repo.save(any(User.class))).thenAnswer(returnsFirstArg()); ``` ## Argument-echo helpers `returnsFirstArg()`, `returnsSecondArg()`, `returnsLastArg()` and the positional `returnsArgAt(int)` all return one argument of the call. The value over a raw lambda is intent: `returnsFirstArg()` says "this collaborator hands the object back" without the reader decoding an index and a cast. `returnsLastArg()` is particularly useful for signatures ending in the interesting parameter, and survives a signature change that adds a leading parameter. ## Sequence helper `returnsElementsOf(Collection)` returns the collection's elements one per invocation. Consecutive `thenReturn(a, b, c)` covers the literal case, but `returnsElementsOf` shines when the sequence is built at runtime - generated ids, a list read from a fixture file, or a list parameterised by the test. Once the elements run out, Mockito keeps returning the last one rather than failing. ## Delegation `delegatesTo(Object target)` forwards each matching call to `target` by matching method signature reflectively, returning whatever the real object returns. Three situations make it valuable: 1. You want mostly real behaviour but still need `verify()` on the interactions - unlike a spy, the mock and the delegate stay separate objects, so calls the delegate makes to *itself* are not recorded. 2. The type cannot be spied cleanly (an interface you only have a hand-written in-memory implementation for). 3. A generated client interface (for example an RPC stub) can be backed by a simple in-process implementation while the test still asserts on calls. The delegate must expose signature-compatible methods; a mismatch fails at call time. And because the delegate is a different object, `this`-referencing behaviour inside it does not route back through the mock. ## Latency `answersWithDelay(long millis, Answer delegate)` sleeps the **calling thread** for the given number of milliseconds, then runs the delegate answer. It exists to test timeout handling, circuit breakers, retry budgets, and racy async code paths against a dependency that is deliberately slow. The cost is real wall-clock time in the suite, and sleeps are a classic source of flakiness on loaded CI machines - a 50 ms delay meant to beat a 100 ms timeout can lose that race. Use short delays, only where the timing is the thing under test, and prefer an injectable clock or a controllable scheduler when the production code allows it. ## Typed lambda adapters `AdditionalAnswers.answer(...)` and `answerVoid(...)` adapt small typed functional interfaces so you can write `answer((String name, Integer age) -> name + age)` instead of pulling arguments out of `InvocationOnMock` by index. This removes the unchecked casts and the index arithmetic, which is the main source of runtime surprises in hand-written answers. It is a readability win in any answer that consumes more than one argument. ## Choosing between helper and lambda Use a helper when one exists: it names the intent and is immune to index typos. Write a lambda when the behaviour is specific to this test - a value derived from the argument, a callback invocation, a conditional throw. Whichever you pick, the answer should be short enough to read at a glance; a large answer, helper-assembled or not, is a sign the test wants a fake rather than a mock.

  • How does delegatesTo differ from wrapping the same object with spy()?
    A spy is the real object instrumented in place, so self-calls inside it go through the instrumentation and are recorded and stubbable. delegatesTo keeps the mock and the delegate as two separate objects: only calls made through the mock are recorded, and the delegate's internal self-calls are invisible. delegatesTo also works when the type cannot be spied, for example when you only have an interface plus a hand-written implementation.
  • What is the risk of testing a timeout with answersWithDelay?
    It burns real wall-clock time and turns a logic assertion into a race between a sleep and a timeout, which a loaded CI machine can lose. Keep the delay well clear of the threshold, use it only where timing is genuinely the subject of the test, and prefer injecting a clock or a controllable executor when the production code allows it.

saying these in an interview costs you the question

  • Reaching for a hand-written lambda with a magic index when returnsFirstArg says it plainly
  • Believing delegatesTo behaves identically to spy(), including self-calls
  • Using answersWithDelay liberally and then blaming CI for flaky, slow tests
  • Expecting returnsElementsOf to throw once the collection is exhausted
  • Thinking these helpers are a different mechanism - they are ordinary Answer instances

context