3 Laws of TDD
Understanding the 3 rules of Test Driven Development is very fundamental in writing clean, stable and consistent code, one that leads to less debugging and instead more refactoring.
Using the Bowling Game Kata to explain these 3 fundamentals of TDD, assuming that one already has an understanding of how the bowling game & score tracker works:
[Code snippets follow C# syntax]
1st Rule of TDD:
Do not write any production code without a failing test first:
In the Bowling game example, the first step is writing a failing test to check whether you can create a bowling game:
[TestMethod]
public void CanCreateGame()
{
var game = new BowlingGame();
}
In the above code snippet, a [test method] CanCreateGame()
is written to see if a Bowling Game is created. We want it to fail.
2nd Rule of TDD:
Write only enough test code as is sufficient enough to fail
From the above example,
[TestMethod]
public void CanCreateGame()
{
var game = new BowlingGame();
}
Creating a game object from the class BowlingGame()
that doesn’t exist yet, would result into a compile error.
[reminder: a compile error is also considered as failing a test]
3rd Rule of TDD:
Only implement a minimal code that makes the failing test pass.
From the above example, it would fail simply because at this point the game object is referencing a type BowlingGame()
that doesn’t exist.
Below is the minimal code that makes the above failing test to pass:
public class BowlingGame() {}
Again, implementing the least amount of code to make the failing test pass.