CodeBlanks Logo Icon CodeBlanks

when thenReturn

Learn behavior imitation with when(...).thenReturn().

when thenReturn

With when(mock).thenReturn(value) you define what a mocked method returns for a given input. The test scenario is then fully under control.

UserRepository repo = mock(UserRepository.class);
when(repo.findById(1)).thenReturn(new User("Alex"));

User u = repo.findById(1);
// u.getName() equals "Alex"

This reproduces a specific scenario without a real database. You can define different return values for different inputs. To throw an exception, use thenThrow.

Throwing exceptions with thenThrow

To make a mocked method throw an exception, use thenThrow. This is an easy way to test error scenarios.

when(repo.findById(99))
    .thenThrow(new UserNotFoundException(99));

The calling code catches the exception with try/catch and verifies the error flow. This lets you test the error path without producing a real error. Error handling code is thus safely tested.

Practice Build stub logic by hand

Define a Discount class with a rateFor(String code) method. The method uses a Map<String, Integer> to return the discount for a code; for unknown codes it returns 0. In a StubDemo class write a main method; add put("SUMMER", 20) and put("WINTER", 15) to the map; print the result of rateFor("SUMMER").

Starter code

Main.java
import java.util.*;

// Define the Discount class (rateFor method uses a Map)

// Write main in StubDemo; add codes to the map and print rateFor's result

Sample solution

Main.java
import java.util.*;

class Discount {
    Map<String, Integer> table = new HashMap<>();
    int rateFor(String code) {
        return table.getOrDefault(code, 0);
    }
}

class StubDemo {
    public static void main(String[] args) {
        Discount d = new Discount();
        d.table.put("SUMMER", 20);
        d.table.put("WINTER", 15);
        System.out.println(d.rateFor("SUMMER"));
    }
}

Expected output

20

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match stubbing methods

Term Meaning
thenReturn Returns a specific value
thenThrow Throws an exception
thenAnswer Produces a custom answer
thenCallRealMethod Calls the real method

2 Complete the thenReturn call

Question
when(repo.findById(1))
    .____(new User("Ayşe"));
Answer
when(repo.findById(1))
    .thenReturn(new User("Ayşe"));

Explanation: thenReturn returns the specific value.

3 What does when(repo.findById(1)).thenReturn(...) do?

  • Defines a return value for the findById(1) call on the repo mock Correct answer
  • Deletes the findById method
  • Calls the findById method
  • Turns repo into a real object

Explanation: This defines a return value for the findById(1) call.

All lessons in Advanced