0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Lesson

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

  1. Stubbing Return Values
  2. Mockito Argument Matchers
  3. Spying on Real Objects
  4. Throwing Exceptions and Consecutive Calls
← Back to Testing Mastery: JUnit, Mockito & Integration Tests