Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Mocks and Stubs

Stubbing Return Values with when and thenReturn

Teach a Mockito mock what to return with when().thenReturn(): argument matching by equals, overriding stubs, returning objects and lists, and common mistakes.

A mock that returns only defaults can test very little. Stubbing is how you give a mock the answers your scenario needs: "when the repository is asked for user 7, return Ana". It is the most used feature of Mockito, and the pattern when(...).thenReturn(...) appears in nearly every test. This lesson covers exactly how the call matches, what happens when stubs overlap, and the mistakes beginners make most often.

Real Mockito lines appear in read-only blocks; every runnable example uses the Mini stand-in from What Is Mockito?. Mini copies the API names and the matching rules described here, so the behavior carries over.

The basic form

Java
import static org.mockito.Mockito.*;

UserRepository users = mock(UserRepository.class);

when(users.findById(7)).thenReturn(Optional.of(new User(7, "Ana")));

Optional<User> found = users.findById(7);      // Optional[User(7, Ana)]
Optional<User> other = users.findById(8);      // Optional.empty(): not stubbed

Read it as a sentence: when users.findById(7) is called, then return this value. Three details are worth remembering:

  1. Arguments are compared with equals. findById(7) matches a call with 7, not 8. For strings and records that means value equality. For your own classes, it means your equals method decides, so give domain objects a proper equals (a record gets one for free).
  2. The return value must fit the method's return type. thenReturn("x") on a method returning int does not compile. For Optional<User> you pass an Optional<User>, not a User.
  3. Everything else stays default. Only the exact call you stubbed is special; calls with other arguments return the default answer (Optional.empty() here).

Try it: exact matching and overriding

Java when / thenReturn in action

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.

Stubs are searched newest first

When two stubbings match the same call, the last one defined wins. That gives you a neat technique: put a general stub in a shared setup method and override it in the one test that needs something different. It also hides a bug: if you stub the same call twice by accident, the first stub is silently dead.

Java
@BeforeEach
void setUp() {
    when(prices.priceOf(anyString())).thenReturn(10.0);   // default for every SKU
}

@Test
void expensiveItem() {
    when(prices.priceOf("DIAMOND")).thenReturn(5000.0);   // overrides only this SKU
    // ...
}

Because the specific stub is declared after the general one, "DIAMOND" gets 5000.0 and every other SKU gets 10.0. If you reversed the order, the general anyString() stub would answer first for everything and the specific stub would never be used. (anyString() is explained in Argument Matchers.)

Returning objects, lists and nested data

thenReturn accepts any object, so you can build small test data inline. Use helper methods or builders to keep tests short; a test that needs ten lines to describe a user is hard to read.

Java
when(orders.findOpenOrders()).thenReturn(List.of(
    anOrder().withId(1).withTotal(20).build(),
    anOrder().withId(2).withTotal(35).build()));

For return types that are interfaces, you can return another mock: when(factory.create()).thenReturn(connectionMock). Chains of mocks returning mocks are a warning sign (see the "Law of Demeter" discussion in the Patterns chapter later), but returning one mock is perfectly normal.

A complete example: arrange, act, assert

Good tests follow three steps, often marked with comments: arrange the stubs and data, act by calling the code under test once, assert the result. Here is a pricing service with a discount rule, tested through stubs:

Java Arrange, act, assert with stubs

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.

isVip("guest") was never stubbed, so it returned the default false; that is exactly the behavior the first test needs. Relying on a default is fine when it is the meaning of the scenario ("not a VIP"), but add a comment or an explicit thenReturn(false) when it would not be obvious to the next reader.

Common mistakes

  • Stubbing a method of the object under test. when(service.quote(...)) on a real object fails, because only mocks and spies can be stubbed. Mockito reports when() requires an argument which has to be 'a method call on a mock'.
  • Forgetting that the setup call is real. when(mock.call()) runs the call on the mock once. That is harmless for a mock, but surprising when the mock's method throws (use doThrow for that, see Stubbing Exceptions).
  • Typo-level mismatches. when(repo.find("ana")) will not match a call made with "Ana". When a stub "does not work", print the real argument.
  • Stubbing everything. Stub only what the scenario needs. Extra stubs hide the point of the test, and with strict stubs (JUnit extension) unused stubs fail the test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Mockito decide whether a call matches when(repo.findById(7))?

    Raw arguments are compared with equals, so equal values match even if they are different objects.
  2. 2. A stub for the same call is defined twice with different return values. What happens?

    Stubbings are searched newest first, so the later definition overrides the earlier one.
  3. 3. What does repo.findByCity("Oslo") return if only "Lyon" is stubbed and the method returns a List?

    An unmatched call falls back to the default answer, which is an empty list for collection return types.
  4. 4. Which line does not compile for a method returning int?

    thenReturn is typed by the return type of the stubbed method, so a String cannot be returned for an int.

Summary

  • when(mock.call(args)).thenReturn(value) defines the answer for that exact call; arguments are compared with equals.
  • Unmatched calls return the default for the return type.
  • The latest matching stub wins, so specific stubs go after general ones.
  • Stub only what the scenario needs, and structure tests as arrange, act, assert.
  • Only mocks and spies can be stubbed, never the real object under test.

Next: Stubbing Exceptions