Unit Testing – Disadvantages of Writing Code Before Unit Tests

code-qualitytddtestingunit testing

I have always seen the recommendation that we should first write unit tests and then start writing code. But I feel that going the other way is much more comfortable (for me) – write code and then the unit tests, because I feel we have much more clarity after we have written the actual code. If I write the code and then the tests, I may have to change my code a little bit to make it testable, even if I concentrate much on creating a testable design. On the other hand, if I write the tests and then the code, the tests will change pretty frequently as and when the code shapes up.

As I see a lot of recommendations to start writing tests and then move on to coding, what are the disadvantages if I do it the other way – write code and then the unit tests?

Best Answer

Red is the answer. Red is what you get from TDD's red-green-refactor cycle that you can't get, test-last. First, write a failing test. Watch it fail. That's your red, and it's important. It says: I have this requirement and I know my code isn't satisfying it. So when you go to step 2 (green), you know, with just as much certainty, that your code now is satisfying that requirement. You know that you've changed your code base in such a way as to satisfy the requirement.

Requirements (tests) developed after the code, based on the code, deprive you of that kind of certainty, that confidence.

Related Topic