Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question

marked as duplicate by gnat, GlenH7, psr, Robert Harvey, World Engineer Jan 23 at 14:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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. –  Stefan Billiet Jan 16 at 9:26
add comment

1 Answer 1

up vote 7 down vote accepted

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.

share|improve this answer
add comment

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