TDD Testing – Meaning of Passing Test Case Without Modifying Production Code

tddtestingunit testing

These are Robert C. Martin's rules for TDD:

  • You are not allowed to write any production code unless it is to
    make a failing unit test pass.
  • You are not allowed to write any more
    of a unit test than is sufficient to fail; and compilation failures
    are failures.
  • You are not allowed to write any more production code
    than is sufficient to pass the one failing unit test.

When I write a test that seems worthwhile but passes without changing production code:

  1. Does that mean I did something wrong?
  2. Should I avoid writing such tests in the future if it can be helped?
  3. Should I leave that test there or remove it?

Note: I was trying to ask this question here: Can I start with a passing unit test? But I wasn't able to articulate the question well enough until now.

Best Answer

It says you can't write production code unless it's to get a failing unit test to pass, not that you can't write a test that passes from the get-go. The intent of the rule is to say "If you need to edit production code, make sure that you write or change a test for it first."

Sometimes we write tests to prove a theory. The test passes and that disproves our theory. We don't then remove the test. However, we might (knowing that we have the backing of source control) break production code, to make sure that we understand why it passed when we didn't expect it to.

If it turns out to be a valid and correct test, and it isn't duplicating an existing test, leave it there.

Related Topic