What if you could make your tests throw errors exactly when you want, like magic?
Why when().thenThrow() for exceptions in JUnit? - Purpose & Use Cases
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.
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.
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.
callRealService(); // hope it throws error sometimes checkIfErrorHandled();
when(mockService.call()).thenThrow(new RuntimeException()); callServiceAndCheckError();
You can easily test how your program reacts to errors without waiting or guessing.
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.
Manual error testing is slow and unreliable.
when().thenThrow() simulates errors on demand.
This makes tests faster, stable, and clear.