The 3 Rules Of TDD
The 3 Rules Of TDD
Test-Driven Development, or TDD for short, seems to be gaining traction in our industry. Becoming familiar with TDD could be a worthwhile investment.
Today I would like to introduce the 3 Rules of TDD:
Rule 1: Only write production code to make a failing unit test pass.
Rule 2: Only write enough of a unit test to make the test fail.
Rule 3: Only write enough production code to make the failing test pass.
What do these rules mean?
Let’s apply them in an example:
In my first article on TDD, ‘A Little TDD‘, we had created a failing unit test to force the creation of a ShoppingCart class.
Unfortunately, ShoppingCart is not yet consistent with the behaviour we’d expect from a new ShoppingCart :
- The shopping cart is empty, and
- The total amount or price to pay is $0.
This definition of behaviour from an empty shopping cart seems obvious – and it is. However, we need to spell it out and define it as clearly as that since computers are not good at handling ambiguity. It’s essential to model a newly constructed, empty shopping cart correctly. Surely we would consider it a bug in our programming if our empty shopping cart cost us at the checkout $5.17!
Ok, let’s get started with the 3 Rules of TDD. We will use them to extend our empty ShoppingCart implementation to have a Total of $0.
Rule 1: Only write production code to make a failing unit test pass.
Sorted – we don’t write any implementation code before we have a failing test – and we don’t have a failing test yet.
Let’s fix that.
Rule 2: Only write enough of a unit test to make the test fail.
We are going to write a test that forces us to address Rule 2. The following small test verifies the Total property on our ShoppingCart to be zero:
This test is failing. The red squiggly underlining of Total is the Integrated Development Environment (IDE) telling us that we have a compilation error. Fair enough – ShoppingCart doesn’t have a Total property. Compilation failures are test failures. So far, so good.
It’s pretty much the shortest unit test we could have written. To comply with Rule 2, we want to write just enough of a test to fail – Done.
Rule 3: Only write enough production code to make the failing test pass.
How do we fix this test? We employ Rule 3 and write the minimum amount of code:
The compilation error in our test has disappeared:
All unit tests pass too, including our the one that checks for a 0 Total:
Hopefully, this article brought a bit of clarity to the 3 Rules of TDD.
Leave a Reply
Want to join the discussion?Feel free to contribute!