0
0
JUnittesting~3 mins

Why doReturn and doThrow in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could make your tests instantly return any result or error without waiting or failing unpredictably?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
when(mock.method()).thenCallRealMethod(); // runs real code, slow and unpredictable
After
doReturn(value).when(mock).method(); // returns value instantly
 doThrow(new Exception()).when(mock).method(); // throws exception instantly
What It Enables

You can quickly and reliably test how your code handles both normal results and errors without depending on real external calls.

Real Life Example

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.

Key Takeaways

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.