Unit Testing – How to Write Unit Tests When One Fix Will Make Many Failing Tests Pass

tddunit testing

I have two test cases to test a fix to code that is using the wrong criteria for selecting objects from a collection:

  1. Given one object in the collection matching the bad criteria, ensure that no object is returned.
  2. Given two objects in the collection, with the later one matching the bad criteria, ensure that the earlier object is retrned.

Right now, both of these tests will fail.

The problem is, as soon as I make the fix, both tests will pass.

Is this ok? I thought we needed a single failing unit test before writing the code. I haven't heard it's ok to have multiple failing unit tests before writing code.

Best Answer

I thought we needed a single failing unit test before writing the code. I haven't heard it's ok to have multiple failing unit tests before writing code.

That's for writing new features, not for fixing bugs, and only if you want to practice ultra-orthodox TDD.

Secondly, an ideal test suite would be one where any bug causes exactly one test to fail, because that makes it easiest to pinpoint where the bug occurs. But this is an ideal that one can aspire to but hardly ever reach, and that's OK. Try to make your unit tests orthogonal if possible, but don't worry if you can't do it all the time.