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 C#, xUnit, and Moq. 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.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

public class InMemoryUserRepository : IUserRepository
{
    private readonly Dictionary<string, User> users = new();
    private int currentId = 1;

    private string GenerateId()
    {
        return (currentId++).ToString();
    }

    public async Task<User> Create(User userData)
    {
        var user = new User
        {
            Id = GenerateId(),
            Email = userData.Email,
            Name = userData.Name,
            CreatedAt = DateTime.Now
        };
        users[user.Id] = user;
        return await Task.FromResult(user);
    }

    public async Task<User> FindById(string id)
    {
        users.TryGetValue(id, out var user);
        return await Task.FromResult(user);
    }

    public async Task<User> FindByEmail(string email)
    {
        var user = users.Values.SingleOrDefault(u => u.Email == email);
        return await Task.FromResult(user);
    }

    public async Task<User> Update(string id, User data)
    {
        if (!users.TryGetValue(id, out var existing))
        {
            return await Task.FromResult<User>(null);
        }

        var updated = new User
        {
            Id = existing.Id, // Prevent id modification
            Email = data.Email ?? existing.Email,
            Name = data.Name ?? existing.Name,
            CreatedAt = existing.CreatedAt // Prevent createdAt modification
        };

        users[id] = updated;
        return await Task.FromResult(updated);
    }

    public async Task<bool> Delete(string id)
    {
        return await Task.FromResult(users.Remove(id));
    }

    public async Task<IList<User>> FindAll()
    {
        return await Task.FromResult(users.Values.ToList());
    }

    public void Clear()
    {
        users.Clear();
        currentId = 1;
    }
}

Explanation:

  • We create an in-memory store for users using a Dictionary.
  • 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 are often quite complicated to build because they mimic the behavior of the real thing. They can be used to verify the state after your code acts on the fake, which can be very useful when you are trying to mimic the environment as best as possible without introducing the uncertainty or delay that the real implementation would introduce.

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