0
0
JUnittesting~15 mins

Fake objects in JUnit - Build an Automation Script

Choose your learning style9 modes available
Use a fake object to test user service without real database
Preconditions (2)
Step 1: Create a fake UserRepository that returns a fixed User for id=1
Step 2: Inject the fake UserRepository into UserService
Step 3: Call UserService.getUserName(1)
Step 4: Verify the returned user name matches the fake user's name
✅ Expected Result: UserService returns the name of the fake user without accessing a real database
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the returned user name equals the expected fake user name
Best Practices:
Use a simple fake class implementing the interface
Avoid using real database or external dependencies
Keep test isolated and fast
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

// User entity
record User(int id, String name) {}

// UserRepository interface
interface UserRepository {
    User findUserById(int id);
}

// UserService uses UserRepository
class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public String getUserName(int id) {
        User user = userRepository.findUserById(id);
        return user != null ? user.name() : null;
    }
}

// Fake UserRepository for testing
class FakeUserRepository implements UserRepository {
    @Override
    public User findUserById(int id) {
        if (id == 1) {
            return new User(1, "FakeUser");
        }
        return null;
    }
}

public class UserServiceTest {

    @Test
    void testGetUserNameReturnsFakeUserName() {
        UserRepository fakeRepo = new FakeUserRepository();
        UserService userService = new UserService(fakeRepo);

        String userName = userService.getUserName(1);

        assertEquals("FakeUser", userName, "UserService should return the fake user's name");
    }
}

This test uses a fake object to replace the real UserRepository. The FakeUserRepository class implements the interface and returns a fixed user when asked for id 1. This avoids any real database calls.

The UserService is created with the fake repository. When getUserName(1) is called, it returns the name from the fake user. The test asserts this name matches the expected "FakeUser" string.

This approach keeps the test fast, isolated, and simple. It shows how to use fake objects to test logic without external dependencies.

Common Mistakes - 3 Pitfalls
Using the real database in the test instead of a fake object
Not implementing the interface methods in the fake object
Hardcoding test data inside the service instead of using a fake
Bonus Challenge

Now add data-driven testing with 3 different user IDs and expected names

Show Hint