What if you could make your tests run instantly and never fail because of outside services?
Why when().thenReturn() stubbing in JUnit? - Purpose & Use Cases
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.
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.
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.
MathService math = new RealMathService(); int result = math.add(2, 3); assertEquals(5, result);
MathService math = mock(MathService.class); when(math.add(2, 3)).thenReturn(5); assertEquals(5, math.add(2, 3));
This lets you test your code in isolation, making tests fast, reliable, and easy to write.
When testing a shopping cart, you can stub the payment service to always approve payments without calling the real bank every time.
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.