TDD Best Practices
Here’s a list of TDD best practices that I have been accumulating in my developer toolbox. Ping me if you think I’m missing anything, and I will add it to the list.
- Have separate source and test folders. Test code should follow the structure of source.
- Test should fail the first time it’s written/run
- Test names should reflect intent, and names should be expressive
- Refactor to remove duplicate code after passing test
- Re-run tests after every refactoring
- Only write new code when a test is failing. Each test should test new/different behavior.
- Write the assertion first
- Minimize the assertions in each test
- All tests should pass before writing the next test
- Only refactor when all tests are passing
- Write the simplest code to pass the test
- Don’t introduce dependencies between tests. Test should pass when run in any order.
- Tests should run fast. A slow test is a test that won’t get run.
- Use mock objects to test code at system boundaries (e.g. database, container, file system) so that tests run fast.
Advertisement

I had to read this sentence twice : “Only refactor when all tests are passing”. I understood that you refactor only when your test suite passes though you mean that we should not refactor in the red.
romain
July 18, 2011 at 3:52 pm
Yes, that is correct.
stevedaskam
July 18, 2011 at 6:56 pm
Great post, although I believe that some of these rules are not for TDD but for Unit Testing
It depends on how someone is viewing the practice. TDD obviously includes all good techniques of Unit Testing so I would propose to add also
- Every one in the team should be able to run the tests.
- Tests should be automated (within a CI envrinoment )
Regards
ppapapetrou
July 22, 2011 at 5:09 am
Nice post. You find my list at http://www.planetgeek.ch/2011/01/04/clean-code-and-clean-tdd-cheat-sheets/ under TDD cheat sheet.
Cheers
Urs
Urs Enzler
July 25, 2011 at 10:19 am
[...] TDD Best Practises(Guidelines, not rules. Short list of quick points to guide developer as they adopt the Test/Code/Refactor TDD cycle.) [...]
Some good reads on Test Driven Development
February 7, 2012 at 2:48 pm