Monday, May 31, 2010

Sustainable Test Driven Development

Growing Object-Oriented Software, Guided by TestsAt QCON, Steve Freeman gave a talk on Sustainable Test Driven Development. Steve show examples of bad tests and gives us advice on how to write good tests that make development easier and easy to maintain. Steve recommends the following:

1. Test Readability: Make sure the tests are readable.

2. Test features and not implementation: Do not write a test for each method in a class, but instead write test for specific features and behaviors.

3. Use helper messages to remove noise and be more expressive.

4. Use self describing variables.

5. Use test data builders that fill in defaults for values not specified.

6. Test the what not the how.

7. Always add message in the assert to explain the test.

8. Overload toString to get descriptive error messages.

9. Specify precisely what should happen and no more.

10. Avoid brittle tests like hardcoding values. For example, when trying to assert for auto-incremental id values, simply test that the value got incremented instead of asserting against an actual value.

Test Driven Development: By Example11. Only enforce order of methods when it matters.
Steve concludes that tests are code too. They need all the same care and attention given to code. Tests need to focus on what matters. We should value expressiveness over convenience and make sure the tests are readable. If a class is hard to test then it’s a clue that our code is too complex.

This presentation is available on InfoQ at http://www.infoq.com/presentations/Sustainable-Test-Driven-Development