We use when().thenReturn() to tell a fake object what to give back when a certain method is called. This helps us test parts of our code without using the real objects.
You want to test a part of your code that depends on another class, but you don't want to use the real class.
You want to control what a method returns to check how your code reacts.
You want to avoid slow or complex operations like database calls during testing.
You want to simulate different responses from a method to test various scenarios.
Syntax
JUnit
when(mockObject.methodCall()).thenReturn(value);
mockObject is the fake object created by Mockito.
methodCall() is the method you want to fake.
Examples
This means when add(2, 3) is called on calculator, it will return 5.
JUnit
when(calculator.add(2, 3)).thenReturn(5);
When getUserName() is called on userService, it returns "Alice".
We create a fake Calculator object. We tell it to return 10 when add(2, 3) is called. Then we check if it actually returns 10.
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Calculator {
int add(int a, int b) {
return a + b;
}
}
public class CalculatorTest {
@Test
void testAddWithStub() {
Calculator calculator = mock(Calculator.class);
when(calculator.add(2, 3)).thenReturn(10);
int result = calculator.add(2, 3);
assertEquals(10, result);
}
}
OutputSuccess
Important Notes
Only stub methods on mock objects, not real objects.
If you don't stub a method, it returns default values like 0, null, or false.
Use when().thenReturn() to control method outputs for predictable tests.
Summary
when().thenReturn() helps fake method results in tests.
It makes tests faster and more focused by avoiding real dependencies.
Always stub only mock objects to avoid errors.
Practice
(1/5)
1. What is the main purpose of when().thenReturn() in JUnit testing?
easy
A. To specify a fake return value for a mocked method call
B. To execute the real method instead of a mock
C. To verify that a method was called
D. To create a new instance of the class under test
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 A
2. Which of the following is the correct syntax to stub a method getName() of a mock object userMock to return "Alice"?
easy
A. thenReturn("Alice").when(userMock.getName());
B. when(userMock.getName()).thenReturn("Alice");
C. userMock.when(getName()).thenReturn("Alice");
D. when(userMock.getName() == "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 B
Quick Check:
Correct syntax = when().thenReturn() [OK]
Hint: Syntax is when(methodCall).thenReturn(value) [OK]
Common Mistakes:
Reversing when() and thenReturn() order
Calling when() on the mock object instead of method
Using equality inside when()
3. Given the code below, what will result print?
List<String> mockList = mock(List.class);
when(mockList.size()).thenReturn(5);
int result = mockList.size();
System.out.println(result);
medium
A. 0
B. null
C. 5
D. Throws NullPointerException
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 C
Quick Check:
Stubbed method returns set value [OK]
Hint: Stubbed methods return thenReturn() value, not default [OK]
Common Mistakes:
Assuming default mock return 0 instead of stubbed 5
Expecting real method execution
Confusing null with int return
4. Identify the error in the following stubbing code:
MyService service = new MyService();
when(service.getData()).thenReturn("Mocked Data");
medium
A. Cannot stub a method on a real object, must mock it first
B. Missing semicolon after thenReturn()
C. Incorrect method name getData()
D. thenReturn() cannot return a String
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 A
Quick Check:
Stub only mocks, not real objects [OK]
Hint: Stub only mock objects, not real instances [OK]
Common Mistakes:
Trying to stub real objects
Ignoring need to mock before stubbing
Assuming thenReturn() syntax error
5. You want to stub a method 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()?
hard
A. when(calculatorMock.calculate(2)).thenReturn(4);
B. when(calculatorMock.calculate(anyInt())).thenReturn(x * 2);
C. when(calculatorMock.calculate(anyInt())).thenReturn(2);
D. when(calculatorMock.calculate(anyInt())).thenAnswer(invocation -> (int) invocation.getArgument(0) * 2);
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 D
Quick Check:
Dynamic return needs thenAnswer(), not thenReturn() [OK]
Hint: Use thenAnswer() for dynamic returns, not thenReturn() [OK]
Common Mistakes:
Trying to compute dynamic values with thenReturn()
Using undefined variable x in thenReturn()
Stubbing only one input value instead of anyInt()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.