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.
Practice
when().thenReturn() in JUnit testing?Solution
Step 1: Understand mocking in tests
Mocking replaces real objects with fake ones to control behavior during tests.Step 2: Role of when().thenReturn()
This syntax sets a fake return value for a method call on a mock object.Final Answer:
To specify a fake return value for a mocked method call -> Option AQuick Check:
when().thenReturn() = fake return value [OK]
- Thinking it calls the real method
- Using it on real objects instead of mocks
- Confusing it with verification methods
getName() of a mock object userMock to return "Alice"?Solution
Step 1: Recall correct when().thenReturn() syntax
The correct order is when(methodCall).thenReturn(value);Step 2: Check each option
when(userMock.getName()).thenReturn("Alice"); matches the correct syntax exactly; others are invalid or reversed.Final Answer:
when(userMock.getName()).thenReturn("Alice"); -> Option BQuick Check:
Correct syntax = when().thenReturn() [OK]
- Reversing when() and thenReturn() order
- Calling when() on the mock object instead of method
- Using equality inside when()
result print?List<String> mockList = mock(List.class); when(mockList.size()).thenReturn(5); int result = mockList.size(); System.out.println(result);
Solution
Step 1: Understand stubbing of mockList.size()
The size() method is stubbed to return 5 whenever called on mockList.Step 2: Check the printed result
Calling mockList.size() returns 5 as stubbed, so result is 5 and prints 5.Final Answer:
5 -> Option CQuick Check:
Stubbed method returns set value [OK]
- Assuming default mock return 0 instead of stubbed 5
- Expecting real method execution
- Confusing null with int return
MyService service = new MyService();
when(service.getData()).thenReturn("Mocked Data");Solution
Step 1: Check object type used in when()
The object service is a real instance, not a mock, so stubbing is invalid.Step 2: Understand mocking requirement
Stubbing works only on mock objects created by mock() or similar methods.Final Answer:
Cannot stub a method on a real object, must mock it first -> Option AQuick Check:
Stub only mocks, not real objects [OK]
- Trying to stub real objects
- Ignoring need to mock before stubbing
- Assuming thenReturn() syntax error
calculate(int x) of a mock calculatorMock to return x * 2 for any integer input. Which is the correct way to do this using when().thenReturn()?Solution
Step 1: Understand when().thenReturn() limitation
thenReturn() returns a fixed value, cannot compute based on input parameter.Step 2: Use thenAnswer() for dynamic return
thenAnswer() allows lambda to compute return based on method arguments.Final Answer:
when(calculatorMock.calculate(anyInt())).thenAnswer(invocation -> (int) invocation.getArgument(0) * 2); -> Option DQuick Check:
Dynamic return needs thenAnswer(), not thenReturn() [OK]
- Trying to compute dynamic values with thenReturn()
- Using undefined variable x in thenReturn()
- Stubbing only one input value instead of anyInt()
Ready to prove it?
Pass the test and this pattern moves unknown
