Search Sreeni's Insights

Filter by content type
crafting June 9, 2015 7 min read

How to do TDD (Test-Driven Development)?

Test-Driven Development explained through the Red-Green-Refactor cycle and a step-by-step fund-universe example built with tests first for practical development and design.

Share:

How to do TDD (Test-Driven Development)?

In the previous article, we discussed how to write unit tests with NUnit and Moq. Most of the teams write the tests after the code is written, if they have time. Often, the time is not there, and the tests are skipped or written only for the easy parts. Test-Driven Development (TDD) turns this around, we write the test first and then write the code to make it pass. It sounds strange initially, but once you practice it, it changes how you design the code. In this article, we are going to see what is TDD, why it is useful, the Red-Green-Refactor cycle and a step by step example.

TL;DR Summary

  • TDD is a development practice where we write a failing test before writing the production code.
  • It follows the Red - Green - Refactor cycle in very small steps.
  • TDD is more a design practice than a testing practice, it drives towards small, decoupled and testable code.
  • Every line of production code has a reason, a test which needed it.
  • It gives a safety net for refactoring from the first day.
  • Start with simple business logic, don’t start with UI or database code.
  • TDD needs practice, expect the first few weeks to be slower.

Challenges

Tests written later are skipped

When the tests are written after the code, they are the first thing to be dropped when the deadline is near. The code goes to production without tests and the technical debt is growing.

Code is hard to test

When the code is written without thinking about the tests, it is usually tightly coupled, with dependencies created inside the methods and big methods doing many things. Writing tests for such code later is very hard, so the developers give up.

Over-engineering

Without a clear goal, developers sometimes write more code than needed, “just in case” for the future requirements. It adds complexity which nobody is using.

What is TDD?

Test-Driven Development (TDD) is a software development practice in which the developer writes an automated test for a small piece of functionality before writing the code that implements it, and then refactors the code while keeping the tests passing. Kent Beck popularised it as part of Extreme Programming (XP).

In simple terms, first we write what the code should do (as a test), then we write the simplest code to do it, then we clean it up.

Think about building a house with a plan approved before construction. The inspector’s checklist (the test) is ready first, then the builder builds exactly what is needed to pass the checklist, nothing more. And every time something is changed, the checklist is run again.

The Red - Green - Refactor cycle

TDD is done in very small cycles of few minutes each. It has the following phases,

TDD cycle: Red (write failing test), Green (make it pass), Refactor (clean up)
TDD cycle: Red (write failing test), Green (make it pass), Refactor (clean up)
  • Red - Write a small test for the next bit of behaviour. Run it and see it fail. If it doesn’t fail, either the behaviour already exists or the test is wrong.
  • Green - Write the simplest code to make the test pass. Don’t worry about the perfect design here, just make it green.
  • Refactor - Now clean up the code and the test, remove duplication, improve names. Run the tests after each change, they must stay green.

Repeat the cycle for the next behaviour. We must travel through these stages iteratively.

Why TDD is important?

In order to get the tests for every behaviour, to design the code which is testable by default and to avoid writing code which is not needed, TDD is a very useful practice. It helps us to,

  • have a full safety net of tests, so refactoring is safe.
  • design small, focused and loosely coupled classes, because hard-to-test code is painful to write test-first.
  • get a fast feedback, we know within seconds when something is broken.
  • keep the focus on the requirement, one behaviour at a time.
  • have the tests as a living documentation of what the code does.

TDD by example

Let us take a simple requirement from our fund domain,

A fund universe can contain a maximum of 50 funds. The same fund cannot be added twice. A closed fund cannot be added.

We will use NUnit for the tests.

Cycle 1: Add a fund to an empty universe

Red - Write the test first. The class FundUniverse doesn’t exist yet, so it doesn’t even compile, which is also “red”.

[Test]
public void AddFund_ToEmptyUniverse_ContainsTheFund()
{
    var universe = new FundUniverse();
    var fund = new Fund { Id = 1 };

    universe.AddFund(fund);

    Assert.That(universe.Funds, Has.Member(fund));
}

Green - Write the simplest code to make it pass.

public class FundUniverse
{
    private readonly List<Fund> _funds = new List<Fund>();

    public IReadOnlyCollection<Fund> Funds
    {
        get { return _funds.AsReadOnly(); }
    }

    public void AddFund(Fund fund)
    {
        _funds.Add(fund);
    }
}

Refactor - Nothing to clean up yet. Move to next behaviour.

Cycle 2: Same fund cannot be added twice

Red

[Test]
public void AddFund_WhenFundAlreadyExists_ThrowsInvalidOperationException()
{
    var universe = new FundUniverse();
    universe.AddFund(new Fund { Id = 1 });

    Assert.Throws<InvalidOperationException>(() => universe.AddFund(new Fund { Id = 1 }));
}

Green

public void AddFund(Fund fund)
{
    if (_funds.Any(f => f.Id == fund.Id))
        throw new InvalidOperationException("Fund " + fund.Id + " already exists in the universe.");

    _funds.Add(fund);
}

Cycle 3: Closed fund cannot be added

Red

[Test]
public void AddFund_WhenFundIsClosed_ThrowsInvalidOperationException()
{
    var universe = new FundUniverse();
    var closedFund = new Fund { Id = 2, Status = FundStatus.Closed };

    Assert.Throws<InvalidOperationException>(() => universe.AddFund(closedFund));
}

Green

public void AddFund(Fund fund)
{
    if (fund.Status == FundStatus.Closed)
        throw new InvalidOperationException("Closed fund " + fund.Id + " cannot be added.");

    if (_funds.Any(f => f.Id == fund.Id))
        throw new InvalidOperationException("Fund " + fund.Id + " already exists in the universe.");

    _funds.Add(fund);
}

Cycle 4: Maximum 50 funds

Red

[Test]
public void AddFund_WhenUniverseIsFull_ThrowsInvalidOperationException()
{
    var universe = new FundUniverse();
    for (var id = 1; id <= 50; id++)
        universe.AddFund(new Fund { Id = id });

    Assert.Throws<InvalidOperationException>(() => universe.AddFund(new Fund { Id = 51 }));
}

Green

if (_funds.Count >= 50)
    throw new InvalidOperationException("Universe cannot contain more than 50 funds.");

Refactor - Now the method has three rules and a magic number. Let us clean it up while the tests keep us safe.

public class FundUniverse
{
    public const int MaxFunds = 50;
    private readonly List<Fund> _funds = new List<Fund>();

    public IReadOnlyCollection<Fund> Funds
    {
        get { return _funds.AsReadOnly(); }
    }

    public void AddFund(Fund fund)
    {
        EnsureFundIsOpen(fund);
        EnsureNotDuplicate(fund);
        EnsureCapacity();

        _funds.Add(fund);
    }

    private static void EnsureFundIsOpen(Fund fund)
    {
        if (fund.Status == FundStatus.Closed)
            throw new InvalidOperationException("Closed fund " + fund.Id + " cannot be added.");
    }

    private void EnsureNotDuplicate(Fund fund)
    {
        if (_funds.Any(f => f.Id == fund.Id))
            throw new InvalidOperationException("Fund " + fund.Id + " already exists in the universe.");
    }

    private void EnsureCapacity()
    {
        if (_funds.Count >= MaxFunds)
            throw new InvalidOperationException("Universe cannot contain more than " + MaxFunds + " funds.");
    }
}
  • Just to pulse check, run all the tests. All four should be green. Now we have a clean class with four tests, and every line of code exists because a test needed it.

Note: In the example, we wrote one test per cycle. In real practice, the cycles are even smaller, sometimes only one line of code per cycle. Small steps keep you in control.

Best Practices

  • Write the smallest failing test - One behaviour per test. If the test needs a lot of setup, the design probably needs to be improved.
  • See it fail first - Always run the test and see it red before writing the code, otherwise you don’t know if the test is really testing something.
  • Simplest code to pass - Don’t write code for the next test in advance.
  • Never skip refactor - Without refactor, TDD produces working but messy code.
  • Keep tests fast - TDD needs running tests every few minutes, slow tests break the rhythm. Mock the database and external services.
  • Start with business logic - Domain rules, calculations and validations are the best place to start with. UI and database code are harder to test-drive.

When TDD is hard?

Keep in mind that TDD is not a silver bullet. It is harder in few cases,

  • Legacy code without tests and with tight coupling. Here, first add characterization tests and break the dependencies, refer the What is a God object and how to break it? article.
  • UI layout and visual design.
  • Exploratory spikes, where you don’t know the solution yet. Do the spike, throw it away and then test-drive the real implementation.

Expect the team to be slower in the first few weeks. It is a skill, and like every skill, it needs practice. Code katas (small exercises like “String Calculator” or “Bowling Game”) are a good way to practice TDD without the pressure of a real project.

Wrap up

In this article, we have looked at what is TDD, the Red-Green-Refactor cycle, why it is important and a step by step example of building a fund universe with tests first. I really appreciate that you took the time to read this article and I hope this article provided you some insights into TDD. In the next article, I will walk you through async and await in C# and the common mistakes like async void and .Result deadlocks.

Related Posts