TDD (Test-Driven Development) means writing tests before writing code. It helps you build reliable, clean code. Here’s a simple step-by-step guide with examples:


Step 1: Set Up a Test Project

Create a test project in your C# solution (e.g., using xUnit or MSTest).

Example:

dotnet new xunit -n MyProject.Tests
dotnet add MyProject.Tests reference MyProject

Step 2: Follow the Red-Green-Refactor Cycle

Red: Write a failing test.

Green: Write minimal code to pass the test.

Refactor: Improve code without breaking tests.

Example: Building a Calculator

Step 2.1: Red Phase

Write a test for an Add method that doesn’t exist yet:

// In MyProject.Tests/CalculatorTests.cs
public class CalculatorTests
{
    [Fact]
    public void Add_TwoNumbers_ReturnsSum()
    {
        // Arrange
        var calculator = new Calculator();

        // Act
        int result = calculator.Add(2, 3);

        // Assert
        Assert.Equal(5, result);
    }
}

This test will fail because Calculator and Add don’t exist yet.


Step 2.2: Green Phase

Write the simplest code to pass the test:

// In MyProject/Calculator.cs
public class Calculator
{
    public int Add(int a, int b)
    {
        return 0; // Temporary code (test will still fail)
    }
}

Run the test again. It fails because Add(2, 3) returns 0, not 5. Fix it:

public int Add(int a, int b)
{
    return a + b; // Now the test passes
}

Step 2.3: Refactor Phase

Improve code without changing behavior. For example:

// Add input validation (optional refactor)
public int Add(int a, int b)
{
    if (a < 0 || b < 0)
        throw new ArgumentException("Numbers must be non-negative");

    return a + b;
}

Update tests to cover new cases (e.g., test for invalid inputs).


Step 3: Repeat for New Features

Add more tests for other features (e.g., Subtract, Multiply):

[Fact]
public void Subtract_TwoNumbers_ReturnsDifference()
{
    var calculator = new Calculator();
    int result = calculator.Subtract(5, 3);
    Assert.Equal(2, result);
}

Write the Subtract method to pass this test.


Tips for Success

  1. Start Small: Focus on one feature at a time.
  2. Test Edge Cases: Test invalid inputs, empty values, etc.
  3. Use Mocking: For dependencies (e.g., databases), use libraries like Moq.
  4. Run Tests Often: Use dotnet test frequently.

Common Pitfalls to Avoid

  • Writing too many tests at once.
  • Skipping the refactor phase.
  • Testing implementation details (focus on behavior instead).

By practicing TDD, you’ll write cleaner code and catch bugs early. Start with simple projects and gradually tackle more complex scenarios! 🚀