Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Spies and Partial Mocks

Stubbing Spies with doReturn

Why when(spy.method()) can run the real method while stubbing, how doReturn, doThrow and doNothing avoid it, and when each style is the better choice.

Stubbing a mock is easy: when(mock.price()).thenReturn(5). Stubbing a spy looks the same but hides a trap. Because a spy runs real code, the call inside when(...) is executed for real while Mockito is still setting up the stub. If that real method has a side effect, is slow, or throws, your test breaks before the stub exists.

Mockito's answer is the doXxx().when(spy).method() family. In this lesson you will see both forms in real Mockito code, run a stand-in that reproduces the problem, and learn a simple rule for choosing.

Mockito is not available on this site. Runnable blocks use the labelled stand-in Mini, which mimics when, doReturn and doThrow on top of java.lang.reflect.Proxy. Real Mockito code appears in read-only blocks.

The trap

Imagine a spy around a service whose real loadRate() calls the network. With real Mockito:

Java
PriceService spy = spy(new PriceService());

// BAD: spy.loadRate() really runs here, while the stub is being written.
when(spy.loadRate()).thenReturn(1.25);

Order of events: Java evaluates spy.loadRate() first (it is the argument of when), so the real network call happens, and may throw ConnectException right on this line. Only afterwards would when receive the result and register the stub.

The safe form reverses the reading order. You first say what to do, then which spy, then which method:

Java
// GOOD: the real method is never invoked.
doReturn(1.25).when(spy).loadRate();

when(spy) here is not the stubbing call from the first form. It only selects the object; the following .loadRate() is recorded as the call to stub, not executed.

The family of do methods

Method Meaning
doReturn(x) Return x when the stubbed method is called
doThrow(ex) Throw ex (works for void methods too)
doNothing() Do nothing in a void method (the default for mocks, useful on spies)
doAnswer(answer) Compute the result from the arguments
doCallRealMethod() Run the real method (useful on mocks, see partial mocks)

They can also be chained for consecutive calls: doReturn(1).doReturn(2).doThrow(new RuntimeException()).when(spy).next().

Reproducing the problem (stand-in)

The real fetch() below throws, like a network call without a network. First we stub with the when style and watch it blow up, then with doReturn.

Java when(spy.x()) runs the real method

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 counter shows exactly one real call, the one that happened inside when(spy.fetch()). After doReturn, calling spy.fetch() returns the stubbed value and the counter stays at 1.

doThrow and doNothing for void methods

when(...) cannot wrap a void method, because there is no value to pass into it. Void methods must always use the do style:

Java
doThrow(new IOException("disk full")).when(writer).flush();
doNothing().when(spy).sendAudit("login");

A spy's void methods run for real by default, so doNothing() is the way to switch off a side effect such as sending an email or writing a file while keeping the rest of the object real.

Java Switch off one side effect

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.

Note that stubbing is per argument: the stub for [email protected] does not affect [email protected]. The stand-in uses doReturn(null) where Mockito has doNothing(), because the stand-in is deliberately small.

Which style should you use?

A good habit that many teams adopt:

  • Mocks: when(...).thenReturn(...). It reads naturally and is type-checked: the compiler rejects thenReturn("text") for an int method.
  • Spies: doReturn(...).when(spy).... It never runs real code.
  • Void methods: always the do family.

doReturn is not type-checked at compile time. If you write doReturn("1.25") for a method that returns double, Mockito reports WrongTypeOfReturnValue when the test runs. That is a small price for avoiding side effects.

A second trap: stubbing the same call twice

With the when style on a spy, re-stubbing runs the previous stub or the real code again. With doReturn the order is simple: the last stub that matches wins, exactly like for mocks. If you need different answers for successive calls, chain them in one statement instead of stubbing repeatedly.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why is when(spy.loadRate()).thenReturn(1.25) risky on a spy?

    Java evaluates spy.loadRate() before when() is entered, so the real code runs once during setup and may throw or cause side effects.
  2. 2. Which stubbing form works for a void method?

    A void method has no value to pass to when(...). Use doThrow, doNothing or doAnswer with the object-first form.
  3. 3. What is the downside of doReturn compared to when/thenReturn?

    doReturn takes an Object, so a wrong type is only found at run time as WrongTypeOfReturnValue.

Summary

  • when(spy.method()) executes the real method during stubbing; doReturn(x).when(spy).method() does not.
  • Use the do family for spies and for every void method: doReturn, doThrow, doNothing, doAnswer.
  • Stubs are per matching call; the most recent matching stub wins.
  • doReturn trades compile-time type safety for safety from side effects.

Next: Partial mocks and callRealMethod