0
0
JUnittesting~15 mins

when().thenReturn() stubbing in JUnit - Build an Automation Script

Choose your learning style9 modes available
Stub a method using when().thenReturn() in JUnit with Mockito
Preconditions (2)
Step 1: Create a mock object of the service class using Mockito.mock()
Step 2: Use Mockito.when() to specify the method call to stub
Step 3: Use thenReturn() to specify the value to return when the method is called
Step 4: Call the stubbed method on the mock object
Step 5: Verify that the returned value matches the stubbed value using an assertion
✅ Expected Result: The stubbed method returns the specified value and the assertion passes
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Assert that the stubbed method returns the expected value
Best Practices:
Use Mockito.mock() to create mock objects
Use when().thenReturn() for stubbing methods
Use assertions from JUnit Jupiter (Assertions.assertEquals)
Keep test methods focused and clear
Use @Test annotation for test methods
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Not creating a mock object before stubbing
Using when() with real method calls instead of mock methods
Forgetting to import static Mockito methods
Bonus Challenge

Now add data-driven testing with 3 different usernames and expected roles using parameterized tests

Show Hint