Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Mocks and Stubs

Consecutive Stubbing and Custom Answers

Return different values on successive calls with chained thenReturn, then compute results from the arguments with thenAnswer for stateful and echoing mocks.

So far every stub gave the same answer each time it was called. Real collaborators do not always behave that way: a job status goes from RUNNING to DONE, a flaky network call fails twice before it works, a repository's save returns the same entity it was given. Mockito covers these cases with consecutive stubbing (a sequence of answers) and with thenAnswer (an answer computed from the call's arguments).

Real Mockito lines are read-only. Runnable examples use the Mini stand-in from What Is Mockito?. One difference to know: in real Mockito an Answer receives an InvocationOnMock and reads arguments with invocation.getArgument(0); the stand-in passes the arguments as a List<Object> and you write args.get(0).

Consecutive return values

Pass several values to thenReturn, or chain several thenReturn calls. Each call to the mock consumes the next value:

Java
when(job.status("job-1")).thenReturn("QUEUED", "RUNNING", "DONE");

job.status("job-1");   // "QUEUED"
job.status("job-1");   // "RUNNING"
job.status("job-1");   // "DONE"
job.status("job-1");   // "DONE": the last value repeats forever

The last value repeats for every further call. If you want to see the sequence end, mix in a thenThrow as the last element. Chaining is equivalent and allows mixing returns and exceptions:

Java
when(client.fetch("/data"))
    .thenThrow(new IOException("reset"))     // 1st call fails
    .thenReturn("payload");                  // 2nd and every later call succeeds

There is also a form for void methods: doThrow(new IllegalStateException()).doNothing().when(mock).run().

Try it: polling a job

Java A sequence of answers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without consecutive stubbing you would have to write a hand-made fake with a counter. Here the sequence reads like a story.

thenAnswer: compute the result

thenReturn always hands out a value fixed at stubbing time. Sometimes the right answer depends on what the code under test passed in. A typical example is a repository's save method, which returns the entity it was given (often with an id filled in). You cannot write a fixed value for that, but you can write an Answer: a small function that runs on every call and receives the arguments.

Real Mockito:

Java
when(users.save(any(User.class)))
    .thenAnswer(invocation -> invocation.getArgument(0));    // return the argument unchanged

invocation.getArgument(0) is the first argument, getArgument(1) the second, and so on; there are also getMethod() and getMock(). A shorter form exists for the common "return the Nth argument" case, AdditionalAnswers.returnsFirstArg().

Try it: echoing and computing

Java thenAnswer reads the arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The id counter lives in an int[] because lambdas can only capture effectively final variables. That is a typical, slightly ugly detail of stateful answers, and a first hint that you should keep answers small.

When to prefer which

You need Use
The same value every time thenReturn(value)
A sequence of different values thenReturn(a, b, c) or chained stubs
An exception at some point thenThrow(...) in the chain
A result computed from the arguments thenAnswer(...)
A real working object a hand-written fake, or a spy

Answers are powerful, but they put logic into the test. Logic in a test is something that can itself be wrong, and the test no longer reads as plain data. If an Answer grows past three or four lines, consider writing a small fake class instead (for example an InMemoryUserRepository). A good fake is shared by many tests and is itself tested once.

Consecutive stubs and strictness

With strict stubs (the JUnit extension) a chained stub counts as "used" as soon as it is called at least once, not when every element of the sequence has been consumed. Conversely, calling it more often than there are values is fine and repeats the last one. You only get a surprise when a sequence is meant to be consumed fully, as in a retry test: add a verify(client, times(3)).fetch("/data") to prove that the loop really ran three times.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With when(m.next()).thenReturn(1, 2, 3), what does the fifth call return?

    After the sequence is used up, the last value (3) is returned for every further call.
  2. 2. Which stubbing makes a call fail once and then succeed?

    Chained stubbing answers in order: the first call throws, the second and later calls return v.
  3. 3. What is thenAnswer best used for?

    An Answer runs on every call and can read the arguments, which a fixed thenReturn cannot.
  4. 4. Why should long Answers be avoided in tests?

    Logic inside a test is a source of bugs. For richer behavior, a small hand-written fake is clearer and reusable.

Summary

  • thenReturn(a, b, c) or chained stubs give a sequence of answers; the last one repeats.
  • Mix thenThrow and thenReturn in a chain to simulate failures followed by success.
  • thenAnswer computes the result from the arguments (invocation.getArgument(n) in real Mockito).
  • Keep answers tiny; prefer a fake class when behavior gets complicated.
  • Verify call counts when a sequence is supposed to be fully consumed.

Next: Default Answers and Void Methods