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.
  1. #1 by romain on July 18, 2011 - 3:52 pm

    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.

    • #2 by stevedaskam on July 18, 2011 - 6:56 pm

      Yes, that is correct.

  2. #3 by ppapapetrou on July 22, 2011 - 5:09 am

    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 )

  3. #4 by Urs Enzler on July 25, 2011 - 10:19 am

    Nice post. You find my list at under TDD cheat sheet.


  1. Some good reads on Test Driven Development
  2. TDD Goodness – Common Technologies – Serious Agile
  3. PHPUnit y buenas prácticas | Jesús L.C.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: