Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Mocks and Stubs

Default Answers and Void Methods

Control what unstubbed mock methods return with RETURNS_SMART_NULLS and deep stubs, and learn doReturn, doNothing, doThrow and doAnswer for void methods.

Two loose ends from the earlier lessons are tied up here. First: what does a mock return for a call you did not stub? You know the default table already; this lesson shows how to change it with a default answer. Second: how do you stub a method that returns nothing? The when(...).thenReturn(...) form cannot express that, so Mockito has the do...() family: doReturn, doNothing, doThrow and doAnswer.

Real Mockito lines are read-only. The runnable examples use the Mini stand-in from What Is Mockito?; its mock(Type.class, fallback) accepts a function that plays the role of Mockito's default Answer. Mini offers no deep stubs or smart nulls; those are shown as real code only.

Built-in default answers

When you create a mock you may pass a second argument that decides what unstubbed calls do. The choices live in the Mockito class as constants:

Java
import static org.mockito.Mockito.*;

Catalog c1 = mock(Catalog.class);                                // RETURNS_DEFAULTS
Catalog c2 = mock(Catalog.class, RETURNS_SMART_NULLS);
Catalog c3 = mock(Catalog.class, RETURNS_DEEP_STUBS);
Catalog c4 = mock(Catalog.class, RETURNS_MOCKS);
Catalog c5 = mock(Catalog.class, CALLS_REAL_METHODS);
Answer Unstubbed calls... Typical use
RETURNS_DEFAULTS return 0, false, empty collections, null (the default) Almost always
RETURNS_SMART_NULLS return the same as above, but a method returning a non-final type gives a smart null that throws a descriptive SmartNullPointerException when used Legacy code where NPEs are hard to trace
RETURNS_MOCKS return a fresh mock (when the type can be mocked) instead of null Rarely; hides missing stubs
RETURNS_DEEP_STUBS return a mock whose own methods are mocks too, so chained calls work Fluent APIs and builders
CALLS_REAL_METHODS run the real method of the class Partial mocks of abstract classes

Deep stubs for call chains

Code such as order.getCustomer().getAddress().getCity() needs three mocks without deep stubs. With RETURNS_DEEP_STUBS you can stub the whole chain in one line:

Java
Order order = mock(Order.class, RETURNS_DEEP_STUBS);
when(order.getCustomer().getAddress().getCity()).thenReturn("Lyon");

Use this sparingly. A test that needs a three-step chain usually points to a class that knows too much about other classes (see the Patterns chapter later in this course). Deep stubs treat the symptom, not the design.

Custom default answers

You can pass your own Answer as the default. Here is the idea with the stand-in. Every unstubbed call to the settings mock answers with a readable placeholder, so a missing stub is easy to spot in the output instead of causing a silent null:

Java A custom default answer

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.

In real Mockito the answer is a lambda taking an InvocationOnMock: mock(Settings.class, invocation -> ...), with invocation.getMethod().getReturnType() giving the return type.

Void methods: the do-family

A void method returns nothing, so when(...) has nothing to wrap. Mockito therefore offers a second syntax in which you start with the action and name the mock afterwards:

Java
doNothing().when(mailer).send(anyString(), anyString());
doThrow(new IllegalStateException("offline")).when(mailer).send(eq("[email protected]"), anyString());
doReturn(42).when(counter).next();
doAnswer(inv -> { System.out.println("sent " + inv.getArgument(0)); return null; })
    .when(mailer).send(anyString(), anyString());
  • doNothing(): makes a void method do nothing. Mock void methods already do nothing, so you need it only to override an earlier doThrow or to chain: doThrow(e).doNothing().when(mock).run() (first call throws, later calls do nothing).
  • doThrow(...): throws; the usual way to fail a void method.
  • doReturn(value): like thenReturn, but safer on spies because it does not call the real method during stubbing, and it is also usable on mocks.
  • doAnswer(...): runs your code for a void method, for example to call a callback passed in as an argument or to record side effects.

The mock goes inside when(...) (not the call!), and the call follows after the closing parenthesis. A typical mistake is writing doThrow(e).when(mailer.send(...)), which does not compile for void and tests the wrong thing otherwise.

Try it: a void method with doNothing, doThrow and doReturn

Java The do-family with a void 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 third work call succeeds again, because the doNothing stub was defined last and therefore answers first.

doReturn vs thenReturn

For mocks both forms behave the same. Two differences remain:

  1. doReturn(value) is not type-checked at compile time: doReturn("text").when(counter).next() compiles and fails at run time with WrongTypeOfReturnValue. thenReturn is checked by the compiler. Prefer when/thenReturn on mocks.
  2. doReturn never calls the method while stubbing. That is essential for spies, where the call inside when(spy.method()) would run real code. The Spies chapter explains it with examples.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does when(mailer.send(a, b)).thenThrow(...) not work for void methods?

    when() needs the return value of the call. For void methods use doThrow(...).when(mock).send(...).
  2. 2. Which default answer returns a mock instead of null, so chained calls work?

    Deep stubs return mocks whose methods are mocks too, which lets you stub a chain like a.b().c() in one line.
  3. 3. A mock method was stubbed with doThrow earlier. How do you make it succeed again?

    Stubbings are searched newest first, so a later doNothing overrides the earlier doThrow.
  4. 4. Why prefer when().thenReturn() over doReturn() for ordinary mocks?

    doReturn takes an Object, so a wrong type is only caught at run time. doReturn is mainly needed for spies and void-like cases.

Summary

  • Unstubbed calls use the mock's default answer: RETURNS_DEFAULTS unless you pass another one to mock(type, answer).
  • RETURNS_DEEP_STUBS helps with call chains but often signals a design problem; CALLS_REAL_METHODS runs real code.
  • For void methods use the do-family: doNothing, doThrow, doAnswer; doReturn also works for non-void.
  • The mock is named in when(mock), and the call follows: doThrow(e).when(mock).run().
  • Prefer when/thenReturn on mocks for compile-time type checking; doReturn is needed for spies.

Next: InjectMocks and Mock Annotations