0
0
JUnittesting~3 mins

Why when().thenThrow() for exceptions in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could make your tests throw errors exactly when you want, like magic?

The Scenario

Imagine you have a program that calls a service to get data. Sometimes, this service might fail and throw an error. If you test this by running the real service every time, you must wait and watch carefully to see if the error happens.

This is like calling a friend to ask for help, but you never know if they will pick up or be busy. You have to keep trying and hope for the best.

The Problem

Testing errors manually is slow and unreliable. You might miss the error if it happens rarely. Also, you cannot control when the error happens, so your tests become flaky and confusing.

It is like trying to catch a rare bird by waiting outside all day without knowing when it will appear.

The Solution

Using when().thenThrow() lets you tell your test exactly when to throw an error. You can simulate the error anytime you want, without calling the real service.

This makes your tests fast, reliable, and easy to understand. You control the error, so you can check how your program handles it perfectly.

Before vs After
Before
callRealService(); // hope it throws error sometimes
checkIfErrorHandled();
After
when(mockService.call()).thenThrow(new RuntimeException());
callServiceAndCheckError();
What It Enables

You can easily test how your program reacts to errors without waiting or guessing.

Real Life Example

Testing a payment system where the payment gateway might fail. Instead of waiting for real failures, you simulate the failure to check if your system shows the right error message to users.

Key Takeaways

Manual error testing is slow and unreliable.

when().thenThrow() simulates errors on demand.

This makes tests faster, stable, and clear.