Test Overview
This test uses a fake object to simulate a database service. It verifies that the service returns the expected user name for a given user ID.
This test uses a fake object to simulate a database service. It verifies that the service returns the expected user name for a given user ID.
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class UserService { private final Database database; UserService(Database database) { this.database = database; } String getUserName(int userId) { return database.getUserNameById(userId); } } interface Database { String getUserNameById(int userId); } class FakeDatabase implements Database { @Override public String getUserNameById(int userId) { if (userId == 1) { return "Alice"; } else { return "Unknown"; } } } public class UserServiceTest { @Test void testGetUserNameReturnsCorrectName() { Database fakeDb = new FakeDatabase(); UserService userService = new UserService(fakeDb); String result = userService.getUserName(1); assertEquals("Alice", result); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner is ready to execute the test method | - | PASS |
| 2 | Creates a FakeDatabase object | FakeDatabase instance is created with hardcoded user data | - | PASS |
| 3 | Creates UserService with the fake database | UserService instance holds reference to FakeDatabase | - | PASS |
| 4 | Calls getUserName(1) on UserService | UserService calls FakeDatabase.getUserNameById(1) | - | PASS |
| 5 | FakeDatabase returns "Alice" for userId 1 | UserService receives "Alice" | - | PASS |
| 6 | Assert that returned name equals "Alice" | JUnit compares expected "Alice" with actual "Alice" | assertEquals("Alice", result) | PASS |
| 7 | Test ends successfully | Test method completes without errors | - | PASS |