Test-Driven Development (TDD)

Write tests first for better code

Posted by Rodrigo Castro on January 9, 2025

Test-Driven Development (TDD) means writing your tests before you write the code.

🔁 The TDD Cycle

  1. Write a failing test (it describes what you want)
  2. Write just enough code to make the test pass
  3. Refactor your code (clean it up)

Repeat!

🧑‍💻 Example

Write a test for IsEven(int n):

1
2
3
4
5
[Fact]
public void IsEven_ReturnsTrue_ForEvenNumbers()
{
    Assert.True(IsEven(4));
}

Then, write the code:

1
bool IsEven(int n) => n % 2 == 0;

📝 Why TDD?

  • Forces you to plan before coding
  • Catches bugs early
  • Makes code easier to change

💡 Try It!

Pick a function you want to write. Write the test first, then the code!

Next: Continuous integration basics!