The importance of tests first in TDD

I see a common mistake with lots of people new to TDD and unit testing in general:

Tests that appear to pass, but really do not.

I have seen a few different ways this can happen:

  • Flat out testing the wrong conditions for passing.
  • Not understanding how the test framework is asserting.
  • Trying to test for too many things in one test, missing the important state for passing.
  • Lazy test, that is written to always pass to get green bar.
  • Writing tests after the fact encourages new developers to make massive wrapper functions to "simplify" writing their tests. Often forgetting to test the wrapper and showing false passes on tests that should fail.

This is a symptom of how the testing was approached. Often people new to TDD want to write code, then test after. As the name implies, tests should drive your development and not the other way around. What do you get when you write tests after the code? Tests that may not capture the actual conditions to pass the tests. They also tend to be fragile to refactoring of the code they test.

The solution is easy:

Write your test first.
Fail that test, like a champ.
Write code to pass, like a victor.
Rinse and repeat.

A few of the perks:

  • It forces you to learn your test framework and understand what you are asking it to assert.
  • You learn to test for as few things as possible to show success.
  • You tend to naturally group and nest your tests to maximize reuse of mocks/spy's/etc.
  • You proved your test can fail, so it is more likely to catch a regression.
Tags// , ,
comments powered by Disqus