Course contentsShow
← C#
Lesson 1649 of 1,90815. Software Quality and TestingFree lesson

Test-Driven Development Workflow

Iterate through the Red-Green-Refactor cycle to design components driven by requirements.

In this lesson, you will learn how to maintain a disciplined development rhythm by iterating through the Red-Green-Refactor cycle to build robust C# components.

The Red-Green-Refactor Cycle

Test-Driven Development (TDD) is not just about writing tests; it is a design process where your tests act as the primary requirements document for your code. The cycle consists of three distinct phases:

  1. Red (Write a Failing Test): Start by writing a test for a single requirement or behavior that does not exist yet. Run it and confirm it fails (ideally for the reason you expect). This forces you to think about the API design from the perspective of the caller rather than the implementer.
  2. Green (Make it Pass): Write the minimum amount of code necessary to make the test pass. Do not over-engineer; if a hardcoded return value satisfies the test, use it for now. This phase proves that the environment is configured correctly and the logic satisfies the requirement.
  3. Refactor (Clean Up): Once the test is green, look at the code you wrote. Improve its structure, remove duplication, and apply design patterns—all while keeping the test passing. If you break something, your existing test will instantly alert you.

Example: Implementing a Simple Calculator

Imagine we need a Calculator that adds two integers.

Red:

[Fact]
public void Add_ShouldReturnSum()
{
    var calc = new Calculator();
    Assert.Equal(5, calc.Add(2, 3)); // This fails because Add doesn't exist.
}

Green:

public class Calculator {
    public int Add(int a, int b) => a + b; // Minimal code to pass.
}

Refactor: If you had implemented a more complex method, this is where you would rename variables, extract interfaces, or simplify logic. Because you have the test, you can refactor with confidence knowing you aren't changing the observed behavior.

By treating the "Red" phase as a way to define your interface and the "Refactor" phase as a way to perfect your implementation, you ensure that every line of code is motivated by a requirement and validated by a test.

Key Takeaway: The TDD cycle forces you to design from the outside in, ensuring that your code is always testable, purposeful, and clean.