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:
- 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
- Fix the production code so that it always returns I. The test will pass.
- Add new test case which asserts that the inverse of a different 2x2 matrix is correct. The test will fail
- Fix the production code so that it calculates the inverse of any 2x2 matrix. The test will pass
- Add new test case with a 3x3 matrix. The test will fail
- Fix the production code so that it calculates the inverse of any size matrix. The test will pass.
- 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
- 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:
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