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 |
stub object in JUnit testing?getValue() to return 5. Options A, C, and D have invalid Java syntax.testService.getValue()?
class TestService {
int getValue() { return 0; }
}
TestService testService = new TestService() {
@Override
int getValue() { return 10; }
};
System.out.println(testService.getValue());getValue() to return 10 instead of 0.testService.getValue() invokes the overridden method, so it returns 10.MyService service = new MyService() {
public int getValue() {
return "five";
}
};getValue() is declared to return int, but returns a String "five".Pass the test and this pattern moves unknown