Wednesday, May 14, 2014

An efficient TDD workflow

How do you do your everyday TDD work? There are many ways to skin a cat, but I like to do it in a cyclic fashion:


I start by writing a very simple failing test. I then implement enough of the production code to just make this test pass. I then add more details to the test which make the test fail again. I implement more of the production code so that it passes again. Rinse and repeat until your tests are covering all the use cases.

Let's say that I want to write a Matrix class with an inversion method. I'd start with a super simple test case where I assert that the inverse of the identity matrix I is an identity matrix. I'd then add more and more cases:

  1. Create test which asserts that the inverse of the unity matrix I is a unity matrix. Production code returns an empty matrix, so it will fail
  2. Fix the production code so that it always returns I. The test will pass.
  3. Add new test case which asserts that the inverse of a different 2x2 matrix is correct. The test will fail
  4. Fix the production code so that it calculates the inverse of any 2x2 matrix. The test will pass
  5. Add new test case with a 3x3 matrix. The test will fail
  6. Fix the production code so that it calculates the inverse of any size matrix. The test will pass.
  7. Add new test case which asserts that calculating the inverse of a singular matrix throws an ArithmetricException. The test will fail because it tries to divide by zero
  8. Fix the production code so that it handles singular matrices correctly. The test will pass.
...and the show goes on until I am satisfied. Note that I'm not writing the entire test and then the entire production code method. Both the test and the production code evolve in parallel -- but I always have a failing test before doing anything with the production code.

Furthermore, I like to have the production code and the test code side-by-side like this so that I don't need to switch back and forth between the files:


If you are using a good test runner like NCrunch, you don't even need to run the tests manually. They are run automatically as you type, and you will have instant feedback when the test fails or passes!


No comments:

Post a Comment