Test Overview
This test uses a stub object to simulate a database service. It verifies that the UserService correctly returns a user name when the stub provides a fixed response.
This test uses a stub object to simulate a database service. It verifies that the UserService correctly returns a user name when the stub provides a fixed response.
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class UserService { private final DatabaseService databaseService; UserService(DatabaseService databaseService) { this.databaseService = databaseService; } String getUserName(int userId) { return databaseService.fetchUserName(userId); } } interface DatabaseService { String fetchUserName(int userId); } class DatabaseServiceStub implements DatabaseService { @Override public String fetchUserName(int userId) { return "Alice"; // fixed stub response } } public class UserServiceTest { @Test void testGetUserNameReturnsStubValue() { DatabaseService stub = new DatabaseServiceStub(); UserService userService = new UserService(stub); String result = userService.getUserName(123); assertEquals("Alice", result); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes the test class UserServiceTest | - | PASS |
| 2 | Creates DatabaseServiceStub instance | Stub object ready to return fixed user name 'Alice' | - | PASS |
| 3 | Creates UserService with stub injected | UserService uses stub instead of real database | - | PASS |
| 4 | Calls getUserName(123) on UserService | UserService calls stub.fetchUserName(123) | - | PASS |
| 5 | Stub returns fixed value 'Alice' | UserService receives 'Alice' from stub | - | PASS |
| 6 | Assert that returned user name equals 'Alice' | Comparing expected 'Alice' with actual 'Alice' | assertEquals("Alice", result) | PASS |
| 7 | Test ends successfully | Test runner reports test passed | - | PASS |