0
0
JUnittesting~3 mins

Why when().thenReturn() stubbing in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could make your tests run instantly and never fail because of outside services?

The Scenario

Imagine you have a calculator app that depends on a complex math service. To test the calculator, you try calling the real math service every time manually.

You have to wait for the real service to respond, and sometimes it gives different answers or takes too long.

The Problem

Manually calling the real service is slow and unreliable.

You might get wrong results if the service changes or is down.

This makes your tests flaky and frustrating to run again and again.

The Solution

Using when().thenReturn() lets you fake the service response easily.

You tell the test exactly what to return when a method is called, so tests run fast and always get the expected answer.

Before vs After
Before
MathService math = new RealMathService();
int result = math.add(2, 3);
assertEquals(5, result);
After
MathService math = mock(MathService.class);
when(math.add(2, 3)).thenReturn(5);
assertEquals(5, math.add(2, 3));
What It Enables

This lets you test your code in isolation, making tests fast, reliable, and easy to write.

Real Life Example

When testing a shopping cart, you can stub the payment service to always approve payments without calling the real bank every time.

Key Takeaways

Manual calls to real services slow down and break tests.

when().thenReturn() stubbing fakes method calls with fixed results.

This makes tests fast, stable, and focused on your code.