Java
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.
Exercise 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").
Show example solution
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"));
}
}
Test yourself
-
Match stubbing methods
- thenReturn
- Returns a specific value
- thenThrow
- Throws an exception
- thenAnswer
- Produces a custom answer
- thenCallRealMethod
- Calls the real method
-
Complete the thenReturn call
when(repo.findById(1))
.____(new User("Ayşe"));
Show answer
when(repo.findById(1))
.thenReturn(new User("Ayşe"));
-
What does when(repo.findById(1)).thenReturn(...) do?
- Defines a return value for the findById(1) call on the repo mock
- Deletes the findById method
- Calls the findById method
- Turns repo into a real object
Show answer
Defines a return value for the findById(1) call on the repo mock — This defines a return value for the findById(1) call.
Next lesson: verify