1

When using TDD, is it bad practice to pass a newly written test with code that could also pass another test? For example, take the following test (in PHP)

public function WhenSomethingIsNull_ThrowsException()
{
    $input = null;
    $this->module->someMethod($input);
}

This could be made to pass with the following code

public function someMethod($input)
{
    if(!$input)
        throw new Exception()
}

This would also pass the test WhenSomethingIsZero_ThrowsException. In these cases, should I fix what I know is wrong with this test in the refactoring step? Or only write code which passes this and only this test?

1
  • 1
    Just be sure that, when writing a new test that would already succeed because of the code you wrote, you disable some part of that code to make the new test fail. You need to see a test fail to make sure you've written it properly. Jan 16, 2014 at 9:26

1 Answer 1

8

No, it isn't bad practice.

The point of TDD is to make sure that all your code is covered by tests. The rule that every test should test one thing only is to promote readability of tests, and is in general reasonable.

But the idea that every possible defect in your code base should trip exactly one test is overkill, and in real-life projects you'll almost never be able to manage such a precise fine-tuning. That's no problem as long as every possible defect raises at least one error in your test suite. Since the point of having a test suite is to make sure it passes all tests at all times, this guarantees the necessary coverage well enough.

Not the answer you're looking for? Browse other questions tagged or ask your own question.