Before reading this post, I recommend reading a previous post of mine along with the comments and trackbacks to related posts.
First, you may wonder why I’m contending that TDD speeds up unit
testing if TDD itself stresses unit testing so much. One can unit
test without employing TDD. I can write some code and write a
unit test for it. If I use this method, I’m likely to have a hard
time unit testing the code because it may call out to a database or the
file system or a web service or some other object that is difficult to
create in isolation. If I think about how I’m going to test the
code as I’m writing it, I’ll end up with code that’s easier to test
because I’ll depend on interfaces and employ other techniques to ensure
my code is loosely coupled.
Because my goal was a piece of code for which it was easy to write a
unit test, I’ll end up with code designed for that. At this
point, I’m blurring the lines between just unit testing and TDD.
I didn’t write my unit test first, but I _thought_ about how I would
write my unit test first. I imagined the method of testing before
writing the code. From this point, it’s a snap to then actually
write the test that’s floating around in my head before coding the
From a pragmatic sense, it probably doesn’t matter which code is
actually typed first if you’ve already decided on the unit test in your
head. You’ve written the unit test in your head before the
production code. The typing is then just semantics.
If you aren’t thinking about unit testing at all (if you don’t
currently do unit testing), then this whole topic is worthless for you,
but if you are attempting to write unit tests after you design your
code, I’m sure you can relate that it’s often difficult because you
have to pull in other classes just to test a single class. If
this happens, then it’s not a unit test at all. It’s an
integration test because it tests multiple things. The difference
in unit testing and integration testing is a topic for another post,
but the difference is very important, and if the difference is not
understood, then arguments for/against TDD don’t make much sense at all.
The above is how TDD speeds up writing unit tests (if you have already been doing unit testing).
If the goal is code with unit tests, then the code will be designed for
easy unit testing. To design for easy unit testing, a developer
has to think about the test first. This leads to mental TDD, and
after the code is designed, the unit test can be written quickly.
The next step would naturally be to just go ahead and type the test
first instead of keeping it in your brain. If at this point you
prefer to continue to type the test after the production code, go
ahead. You will have benefited some by focusing more on how to
test the code.