What if you could make your tests instantly return any result or error without waiting or failing unpredictably?
Why doReturn and doThrow in JUnit? - Purpose & Use Cases
Imagine you are testing a method that calls another method which might return a value or throw an error. You try to test this by running the real code every time.
But what if the called method depends on a database or external service? You have to wait, and sometimes it fails unpredictably.
Manually running the real method slows down tests a lot. It also makes tests unreliable because external factors can cause failures.
It is hard to test error cases because you cannot easily force the method to throw an exception.
Using doReturn and doThrow lets you control what the called method does during tests.
You can make it return a specific value or throw an exception instantly, without running the real code.
This makes tests fast, reliable, and easy to write for both success and error cases.
when(mock.method()).thenCallRealMethod(); // runs real code, slow and unpredictabledoReturn(value).when(mock).method(); // returns value instantly doThrow(new Exception()).when(mock).method(); // throws exception instantly
You can quickly and reliably test how your code handles both normal results and errors without depending on real external calls.
Testing a payment service method that calls a bank API: use doReturn to simulate a successful payment response, and doThrow to simulate a network failure, all without calling the real bank API.
doReturn lets you fake a method's return value easily.
doThrow lets you simulate exceptions to test error handling.
Both make tests faster, more reliable, and simpler to write.