Stub a method using when().thenReturn() in JUnit with Mockito
Preconditions (2)
✅ Expected Result: The stubbed method returns the specified value and the assertion passes
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class UserService { public String getUserRole(String username) { // Imagine this calls a database or external service return "Unknown"; } } public class UserServiceTest { @Test void testGetUserRoleStub() { // Create mock UserService mockService = mock(UserService.class); // Stub method when(mockService.getUserRole("admin")).thenReturn("Administrator"); // Call stubbed method String role = mockService.getUserRole("admin"); // Assert returned value assertEquals("Administrator", role); } }
This test creates a mock of UserService using Mockito. Then it stubs the getUserRole method to return "Administrator" when called with "admin". The test calls the stubbed method and asserts the returned value matches the stubbed value. This shows how when().thenReturn() works for stubbing methods in unit tests.
Now add data-driven testing with 3 different usernames and expected roles using parameterized tests
when().thenReturn() in JUnit testing?getName() of a mock object userMock to return "Alice"?result print?List<String> mockList = mock(List.class); when(mockList.size()).thenReturn(5); int result = mockList.size(); System.out.println(result);
MyService service = new MyService();
when(service.getData()).thenReturn("Mocked Data");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()?Pass the test and this pattern moves unknown