Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Strictness and Extensions

Mock Settings and Default Answers

Configure mocks with withSettings(), choose a default answer such as RETURNS_SMART_NULLS or RETURNS_DEEP_STUBS, write custom Answers, and name mocks for clearer errors.

Every mock has a default answer: what it returns for a call you did not stub. The built-in default is friendly but blunt: 0, false, null, an empty collection, Optional.empty(). Mockito lets you change that behavior and a few other properties of a mock through settings. This lesson covers the settings that matter in practice and builds a stand-in so you can see what a default answer actually is.

Mockito is not available on this site. Real Mockito code is read-only; the runnable code is a labelled stand-in built on the Mini library.

The default: RETURNS_DEFAULTS

For an unstubbed method the standard answer, RETURNS_DEFAULTS, returns:

Return type Value
int, long, double... 0
boolean false
String, other objects null
List, Set, Map, Collection empty collection
Optional, Stream empty

Everything else is null. That is why mock.findUser(1).getName() throws NullPointerException unless you stub findUser.

Other built-in answers

Java
import static org.mockito.Answers.*;

Foo a = mock(Foo.class, RETURNS_SMART_NULLS);   // null becomes a "smart" object that throws a helpful exception
Foo b = mock(Foo.class, RETURNS_MOCKS);         // returns mocks for non-final return types
Foo c = mock(Foo.class, RETURNS_DEEP_STUBS);    // chained calls a().b().c() return mocks automatically
Foo d = mock(Foo.class, CALLS_REAL_METHODS);    // partial mock, see earlier lesson
Foo e = mock(Foo.class, RETURNS_SELF);          // methods returning the mock's own type return the mock (builders)
Answer Use it when
RETURNS_SMART_NULLS You want a clear message instead of a bare NullPointerException when an unstubbed result is dereferenced
RETURNS_MOCKS Wide object graphs where you only care about a few calls
RETURNS_DEEP_STUBS Chained APIs; see Deep stubs and the Law of Demeter
CALLS_REAL_METHODS Partial mocks (lesson)
RETURNS_SELF Fluent builders such as builder.name("x").age(3)

withSettings()

withSettings() collects options and is the second argument of mock:

Java
PaymentGateway gateway = mock(PaymentGateway.class, withSettings()
        .name("gateway")                      // used in error messages and verification output
        .defaultAnswer(RETURNS_SMART_NULLS)
        .extraInterfaces(AutoCloseable.class) // the mock also implements AutoCloseable
        .strictness(Strictness.LENIENT)       // per-mock strictness
        .stubOnly()                           // no verification data kept (saves memory)
        .serializable());                     // can be serialized

Useful options:

  • name("..."): when two mocks have the same type, the name tells you which one failed.
  • lenient() or strictness(...): relax strict stubs for one mock (next lesson).
  • stubOnly(): for mocks used only to feed data. Verifying a stub-only mock throws an error, which also documents intent.
  • useConstructor(...): run a real constructor (used for abstract classes).
  • spiedInstance(obj): the spy settings behind spy(obj).
  • verboseLogging(): prints every call and stub use to the console, handy for debugging a puzzling test.

Writing your own Answer

An Answer receives the invocation and computes the result. Real Mockito:

Java
when(repo.save(any(User.class))).thenAnswer(invocation -> {
    User user = invocation.getArgument(0);
    user.setId(42L);                 // simulate the database assigning an id
    return user;
});

A default answer is the same interface applied to every unstubbed call:

Java
Answer<Object> failOnUnstubbed = invocation -> {
    throw new IllegalStateException("Unexpected call: " + invocation.getMethod().getName());
};
Repo repo = mock(Repo.class, failOnUnstubbed);

That makes a "strict mock" that reports any call you did not plan.

Default answers in the stand-in

In Mini, a mock's fallback field is its default answer. The program below installs three different ones on mocks of the same interface and calls an unstubbed method on each.

Java Three default answers for one interface

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 first line shows empty list, empty Optional, 0 and null. The second shows that the strict answer fails fast with a precise message. The third shows that a stub still wins over the default (Ada), which is how it works in Mockito too: stubs first, default answer for the rest.

Answers in tests: a fake database id

thenAnswer is the right tool when a result depends on the argument. This stand-in simulates a repository that assigns ids:

Java thenAnswer: compute the result from the argument

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 stand-in has no argument matchers, so the stub is created for the exact ana instance; with real Mockito you would write when(repo.save(any(User.class))).thenAnswer(...) and it would serve every user (see the matchers chapter).

When not to customize

Default answers are powerful, but they hide behavior. If a test relies on RETURNS_MOCKS to avoid stubbing, readers cannot see what the code needs. Prefer explicit stubs, and use special answers in helper factories where the intent is named, for example strictMock(Repo.class).

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. What does an unstubbed List-returning method return by default?

    RETURNS_DEFAULTS returns empty collections and empty Optionals, zero for numbers, false for booleans and null for other objects.
  2. 2. Which setting makes a mock easier to identify in failure messages when you have two mocks of one type?

    name() appears in verification and stubbing error output.
  3. 3. In which order are a stub and the default answer applied to a call?

    Stubbing overrides the default answer for the matching call; everything else falls to the default.

Summary

  • A default answer decides what unstubbed calls return; the built-in one gives zero, false, null, empty collections.
  • Built-ins include RETURNS_SMART_NULLS, RETURNS_MOCKS, RETURNS_DEEP_STUBS, CALLS_REAL_METHODS and RETURNS_SELF.
  • withSettings() sets name, answer, extra interfaces, strictness, stub-only, serializable, constructor use and more.
  • Use thenAnswer to compute results from arguments, and a custom default answer for strict mocks.
  • Explicit stubs usually read better than clever defaults.

Next: BDD style and lenient stubbing