Isolating Dependencies with Test Doubles: Fakes

Introduction to Fakes in TDD

Welcome to our lesson on using Fakes as test doubles in Test Driven Development (TDD) with Java, JUnit, and Mockito. In this lesson, you'll explore how fakes can streamline your testing by simulating real-world components. Our journey so far has exposed you to various test doubles like dummies, stubs, spies, and mocks. Now, we'll dive into fakes, which enable you to create realistic implementations that mirror complex dependencies, making your tests more robust and reliable. As always, we'll practice the TDD cycle: Red, Green, Refactor, as we see how fakes fit into our testing strategy.

Code Example and Walkthrough: Implementing an In-memory Fake Repository

Let's see how to implement a simple fake: an InMemoryUserRepository. This serves as a stand-in for a real database repository, providing controlled behavior for our tests.

Create a class InMemoryUserRepository.java:

public class InMemoryUserRepository implements IUserRepository {
    private final Map<String, User> users = new ConcurrentHashMap<>();
    private int currentId = 1;

    private synchronized String generateId() {
        return String.valueOf(currentId++);
    }

    @Override
    public User create(User userData) {
        User user = new User();
        user.setId(generateId());
        user.setEmail(userData.getEmail());
        user.setName(userData.getName());
        user.setCreatedAt(LocalDateTime.now());
        users.put(user.getId(), user);
        return user;
    }

    @Override
    public User findById(String id) {
        return users.get(id);
    }

    @Override
    public User findByEmail(String email) {
        return users.values().stream()
                .filter(u -> u.getEmail().equalsIgnoreCase(email))
                .findFirst()
                .orElse(null);
    }

    @Override
    public User update(String id, User data) {
        User existing = users.get(id);
        if (existing == null) {
            return null;
        }

        if (data.getEmail() != null) {
            existing.setEmail(data.getEmail());
        }
        if (data.getName() != null) {
            existing.setName(data.getName());
        }
        // Prevent modification of id and createdAt
        users.put(id, existing);
        return existing;
    }

    @Override
    public boolean delete(String id) {
        return users.remove(id) != null;
    }

    @Override
    public List<User> findAll() {
        return new ArrayList<>(users.values());
    }

    @Override
    public void clear() {
        users.clear();
        currentId = 1;
    }
}

Explanation:

  • We create an in-memory store for users using a ConcurrentHashMap.
  • Each function simulates typical database operations such as creating and finding users.
  • The clear method ensures data isolation between tests, a crucial feature for repeatable outcomes.

By having a controlled data store, we make sure our tests are focused on business logic and not dependent on an external database. Fakes often mimic the behavior of real components, providing a safe and predictable testing environment without the complexity of external systems.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal