Skip to content

Passing In What You Depend On

The Course
•
30 min study

Code that creates its own file writer, reads the real clock and prints to the console is difficult to test, because each test touches real things. The fix sounds grand but is simple: instead of a class creating what it needs, it receives it. That's called dependency injection.

The trouble with reaching out

CarelessLogger decides for itself where to write. A test would have to read a real file and clean up afterwards, and it would pass or fail depending on what's already there.

Decided inside C#
var logger = new CarelessLogger();
logger.Log("started");
Console.WriteLine(File.ReadAllText("app.log").Trim());

class CarelessLogger
{
    public void Log(string message)
    {
        File.AppendAllText("app.log", message + "\n");
    }
}
Check your prediction
Text
started

Receive an interface

Declare what's needed as an interface, and take it in the constructor. Now the class doesn't know or care where its messages go. The real program passes a real implementation, and a test passes a fake that remembers what it received.

Decided outside C#
var fake = new FakeSink();
var service = new Greeter(fake);

service.Greet("Ana");
service.Greet("");

Console.WriteLine(fake.Lines.Count);
Console.WriteLine(fake.Lines[0]);
Console.WriteLine(fake.Lines[1]);

new Greeter(new ConsoleSink()).Greet("Ben");

interface ISink
{
    void Write(string line);
}

class ConsoleSink : ISink
{
    public void Write(string line)
    {
        Console.WriteLine(line);
    }
}

class FakeSink : ISink
{
    public List<string> Lines { get; } = new();

    public void Write(string line)
    {
        Lines.Add(line);
    }
}

class Greeter
{
    private readonly ISink sink;

    public Greeter(ISink sink)
    {
        this.sink = sink;
    }

    public void Greet(string name)
    {
        sink.Write(name.Length == 0 ? "Hello, stranger" : $"Hello, {name}");
    }
}
Check your prediction
Text
2
Hello, Ana
Hello, stranger
Hello, Ben

Fakes can fail on demand

A disk that's full is hard to arrange for a test. A fake can do it with one line. This is one of the best reasons to use the pattern: you can test the failure paths, which usually have the most bugs. Here a primary constructor (the parameters right after the class name) also trims the boilerplate.

Failure on demand C#
Console.WriteLine(new Backup(new FakeStore()).Run("data"));
Console.WriteLine(new Backup(new FakeStore { Fail = true }).Run("data"));

interface IStore
{
    void Save(string data);
}

class FakeStore : IStore
{
    public bool Fail { get; init; }

    public void Save(string data)
    {
        if (Fail)
        {
            throw new IOException("disk full");
        }
    }
}

class Backup(IStore store)
{
    public string Run(string data)
    {
        try
        {
            store.Save(data);
            return "saved";
        }
        catch (IOException e)
        {
            return $"failed: {e.Message}";
        }
    }
}
Check your prediction
Text
saved
failed: disk full

A delegate can be enough

An interface with one method can often be just a Func. For one small dependency, this is simpler. For a group of related methods, or something with state, an interface reads better. The real program creates everything in one place, near its start, and hands it to whatever needs it. Large applications use a container library to do this wiring, but it's the same idea.

A small dependency as a Func C#
var counts = new Dictionary<string, int> { ["a"] = 2 };

Console.WriteLine(Format("a", key => counts.GetValueOrDefault(key)));
Console.WriteLine(Format("b", key => counts.GetValueOrDefault(key)));
Console.WriteLine(Format("any", key => 99));

static string Format(string key, Func<string, int> lookup) => $"{key}={lookup(key)}";
Check your prediction
Text
a=2
b=0
any=99

Fix it: The fake that was never used

This test hands Shop a fake mailer and counts what it sent. Predict the count, then run it.

The fake that was never used C#
var fake = new FakeMailer();
var shop = new Shop(fake);
shop.Order("Ana");
Console.WriteLine($"fake sent {fake.Sent}");

interface IMailer
{
    void Send(string to);
}

class RealMailer : IMailer
{
    public void Send(string to) => Console.WriteLine($"(a real email to {to})");
}

class FakeMailer : IMailer
{
    public int Sent { get; private set; }

    public void Send(string to) => Sent++;
}

class Shop
{
    private readonly IMailer mailer;

    public Shop(IMailer mailer)
    {
        this.mailer = new RealMailer();
    }

    public void Order(string customer) => mailer.Send(customer);
}
Check your prediction
Text
(a real email to Ana)
fake sent 0

A real email went out, and the fake counted nothing. The constructor takes a mailer but then makes its own, so the test checked nothing while sending a real message. Nothing in the compiler complains. Fix Shop.

Fix it

Store the mailer you were given:

C#
var fake = new FakeMailer();
var shop = new Shop(fake);
shop.Order("Ana");
Console.WriteLine($"fake sent {fake.Sent}");

interface IMailer
{
    void Send(string to);
}

class RealMailer : IMailer
{
    public void Send(string to) => Console.WriteLine($"(a real email to {to})");
}

class FakeMailer : IMailer
{
    public int Sent { get; private set; }

    public void Send(string to) => Sent++;
}

class Shop
{
    private readonly IMailer mailer;

    public Shop(IMailer mailer)
    {
        this.mailer = mailer;
    }

    public void Order(string customer) => mailer.Send(customer);
}
Text
fake sent 1

This is why a fake should record something that the test then checks. A fake that only stays quiet would have let this bug pass. Creating real dependencies belongs in one place at the top of the program, never inside the class that uses them.

Your turn

Exercise

An order service with fakes

Define IPayment with bool Charge(decimal amount), and IMailer with void Send(string text). Write OrderService, which receives both. Place(decimal amount) returns invalid if the amount is 0 or below, without charging; returns declined if the charge fails, without sending mail; otherwise it sends the mail Thanks for 25 and returns placed.

Write fakes that record calls, and test all three paths. For each one print the result, the number of charges, and the number of mails.

When it works, it prints:

Text
invalid, charges 0, mails 0
declined, charges 1, mails 0
placed, charges 1, mails 1
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

The important checks are what didn't happen: no charge for an invalid amount, and no mail for a declined one. Your fakes need counters to see that.

Hint 2: a first step

Write the two interfaces and the two fakes before the service. Give FakePayment an Approve property that a test can set.

Show one solution
C#
Try(0m, true);
Try(25m, false);
Try(25m, true);

static void Try(decimal amount, bool approve)
{
    var payment = new FakePayment { Approve = approve };
    var mailer = new FakeMailer();
    string result = new OrderService(payment, mailer).Place(amount);
    Console.WriteLine($"{result}, charges {payment.Charges}, mails {mailer.Sent.Count}");
}

interface IPayment
{
    bool Charge(decimal amount);
}

interface IMailer
{
    void Send(string text);
}

class OrderService(IPayment payment, IMailer mailer)
{
    public string Place(decimal amount)
    {
        if (amount <= 0m)
        {
            return "invalid";
        }
        if (!payment.Charge(amount))
        {
            return "declined";
        }
        mailer.Send($"Thanks for {amount}");
        return "placed";
    }
}

class FakePayment : IPayment
{
    public bool Approve { get; init; }
    public int Charges { get; private set; }

    public bool Charge(decimal amount)
    {
        Charges++;
        return Approve;
    }
}

class FakeMailer : IMailer
{
    public List<string> Sent { get; } = new();

    public void Send(string text)
    {
        Sent.Add(text);
    }
}
Text
invalid, charges 0, mails 0
declined, charges 1, mails 0
placed, charges 1, mails 1

OrderService receives both dependencies as interfaces, so the test decides how each behaves: Approve makes the payment succeed or fail on demand. The fakes record what happened, and each line checks the order of decisions: an invalid amount charges nothing, a declined payment sends no email, and only a placed order does both.

Was this article helpful?

Your response is saved on this device.