Throwing Exceptions and Consecutive Calls
Stub mocks to throw exceptions and to return different values across consecutive invocations for richer test scenarios.
Throwing Exceptions and Consecutive Calls is a free Testing Mastery: JUnit, Mockito & Integration Tests lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Testing Mastery: JUnit, Mockito & Integration Tests learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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());Testing the Failure Path
Combine the throwing stub with assertThrows to verify your code reacts correctly.
@Test
void propagatesError() {
when(repo.findById(99L)).thenThrow(new NotFoundException());
assertThrows(NotFoundException.class,
() -> service.load(99L));
}Throwing from void Methods
For void methods you cannot use when(...) directly. Use doThrow(...).when(mock).method() instead.
doThrow(new IllegalStateException())
.when(logger).flush();Consecutive Return Values
Pass multiple arguments to thenReturn to return different values on successive calls. The last value repeats once exhausted.
when(counter.next())
.thenReturn(1, 2, 3);Chaining Stub Calls
You can also chain calls. Each call describes the next invocation in order.
when(counter.next())
.thenReturn(1)
.thenReturn(2)
.thenThrow(new IllegalStateException());Mixing Returns and Throws
A common pattern: succeed a few times, then fail. This models flaky resources like a retrying network client.
when(client.fetch())
.thenReturn("ok")
.thenThrow(new IOException("down"));Checked Exceptions Caveat
A mock can only throw a checked exception that the stubbed method declares. Throwing an undeclared checked exception causes a runtime error from Mockito.
doReturn for Consecutive Values
The do* family also supports chaining and is required when stubbing spies or void methods.
doReturn("a")
.doReturn("b")
.when(provider).value();Why This Matters
Exception and consecutive stubbing let you exercise retry logic, fallback paths, and stateful sequences without building complex fake objects.
Putting It Together
You can now drive a mock through a full sequence of success and failure to validate resilient code.
when(api.call())
.thenReturn("first")
.thenThrow(new TimeoutException());Quick Check
How do you make a stubbed method return 1, then 2 on its second call?
Recap
You learned advanced stubbing:
thenThrow/doThrowsimulate errors- Multiple
thenReturnargs or chains give consecutive values - Mocks can only throw declared checked exceptions
- Use
do*for void methods and spies
Frequently asked questions
Is the “Throwing Exceptions and Consecutive Calls” lesson free?
Yes — the full text of “Throwing Exceptions and Consecutive Calls” is free to read here on the web, and the Testing Mastery: JUnit, Mockito & Integration Tests course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Testing Mastery: JUnit, Mockito & Integration Tests course, upgrade to CoddyKit PRO.
What will I learn in “Throwing Exceptions and Consecutive Calls”?
Stub mocks to throw exceptions and to return different values across consecutive invocations for richer test scenarios. You practise Testing Mastery: JUnit, Mockito & Integration Tests with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Testing Mastery: JUnit, Mockito & Integration Tests?
No prior experience is required. Testing Mastery: JUnit, Mockito & Integration Tests on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Throwing Exceptions and Consecutive Calls” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Testing Mastery: JUnit, Mockito & Integration Tests lesson?
Yes. Every Testing Mastery: JUnit, Mockito & Integration Tests lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Stubbing Return Values
- Mockito Argument Matchers
- Spying on Real Objects
- Throwing Exceptions and Consecutive Calls