Throwing Exceptions and Consecutive Calls
Stub mocks to throw exceptions and to return different values across consecutive invocations for richer test scenarios.
Beyond Simple Returns
Stubbing return values covers the happy path, but real code must also handle errors and changing state. Mockito lets you stub mocks to throw exceptions and to vary their answers per call.
thenThrow Basics
Use thenThrow to make a stubbed method raise an exception, so you can test your error handling.
when(repo.findById(99L))
.thenThrow(new NotFoundException());All lessons in this course
- Stubbing Return Values
- Mockito Argument Matchers
- Spying on Real Objects
- Throwing Exceptions and Consecutive Calls