0
0
JUnittesting~10 mins

Stub objects in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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);
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes the test class UserServiceTest-PASS
2Creates DatabaseServiceStub instanceStub object ready to return fixed user name 'Alice'-PASS
3Creates UserService with stub injectedUserService uses stub instead of real database-PASS
4Calls getUserName(123) on UserServiceUserService calls stub.fetchUserName(123)-PASS
5Stub returns fixed value 'Alice'UserService receives 'Alice' from stub-PASS
6Assert that returned user name equals 'Alice'Comparing expected 'Alice' with actual 'Alice'assertEquals("Alice", result)PASS
7Test ends successfullyTest runner reports test passed-PASS
Failure Scenario
Failing Condition: Stub returns a different value or null
Execution Trace Quiz - 3 Questions
Test your understanding
What is the main purpose of the stub object in this test?
ATo test the real database connection
BTo simulate the database service with a fixed response
CTo replace the UserService logic
DTo generate random user names
Key Result
Using stub objects helps isolate the unit under test by replacing external dependencies with simple fixed responses, making tests reliable and fast.