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.
0
0
when().thenReturn() stubbing in JUnit
Introduction
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".JUnit
when(userService.getUserName()).thenReturn("Alice");Sample Program
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.