0
0
JUnittesting~10 mins

Fake objects in JUnit - Test Execution Trace

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

Test Code - JUnit
JUnit
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);
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner is ready to execute the test method-PASS
2Creates a FakeDatabase objectFakeDatabase instance is created with hardcoded user data-PASS
3Creates UserService with the fake databaseUserService instance holds reference to FakeDatabase-PASS
4Calls getUserName(1) on UserServiceUserService calls FakeDatabase.getUserNameById(1)-PASS
5FakeDatabase returns "Alice" for userId 1UserService receives "Alice"-PASS
6Assert that returned name equals "Alice"JUnit compares expected "Alice" with actual "Alice"assertEquals("Alice", result)PASS
7Test ends successfullyTest method completes without errors-PASS
Failure Scenario
Failing Condition: FakeDatabase returns a different name or null for userId 1
Execution Trace Quiz - 3 Questions
Test your understanding
What is the purpose of the FakeDatabase in this test?
ATo connect to the real database and fetch data
BTo simulate the database behavior without using a real database
CTo test the database connection speed
DTo replace the UserService class
Key Result
Using fake objects helps isolate the unit under test by replacing real dependencies with simple, controlled implementations. This makes tests faster and more reliable.