Test Driven Development (TDD): A Practical Introduction
Test Driven Development (TDD) is a disciplined approach to software development where you write tests before you write the code. Instead of coding and hoping nothing breaks, TDD gives you a safety net and a clear workflow for building robust features.
In this post, we’ll break down the TDD cycle, address common misconceptions, and walk through a simple example in C#.
The TDD Cycle: Red, Green, Refactor
- Red: Write a test for a new feature. It should fail, since the feature doesn’t exist yet.
- Green: Write the minimum code needed to make the test pass.
- Refactor: Clean up the code, keeping all tests green.
This loop is repeated for every new piece of functionality. It’s simple, but it fundamentally changes how you design and maintain code.
Common Myths About TDD
- “TDD slows you down.” It may feel slower at first, but it saves hours of debugging and regression fixes in the long run.
- “TDD is just about testing.” Actually, TDD is a design technique. Tests guide your architecture and help you write modular, maintainable code.
- “TDD only works for simple problems.” TDD is even more valuable for complex domains, where breaking problems into small, testable steps is crucial.
A Simple Example: Adding Two Numbers
Let’s see TDD in action with a basic C# example. Suppose we want a method that adds two numbers.
- Write a failing test (Red):
using Xunit;
public class CalculatorTests
{
[Fact]
public void Add_TwoNumbers_ReturnsSum()
{
var calc = new Calculator();
var result = calc.Add(2, 2);
Assert.Equal(4, result);
}
}
Code Sample #1 : Failing test for Add method
This test fails because Calculator
doesn’t exist yet.
- Write minimal code to pass (Green):
public class Calculator
{
public int Add(int a, int b) => a + b;
}
Code Sample #2 : Minimal code to pass the test
Now the test passes. If the code is already clean, you may not need to refactor. In real projects, this is where you improve names, remove duplication, or reorganize logic—confident that your tests have your back.
Why TDD Matters
TDD isn’t about writing more tests. It’s about building confidence in your codebase, enabling safe refactoring, and letting tests drive better design decisions. The process scales from trivial methods to complex systems.
In the next post, we’ll tackle a slightly more complex problem (like FizzBuzz or a String Calculator) and walk through the TDD process step by step.
Have you tried TDD before? What worked, what didn’t? Share your experience in the comments below.