April 7, 2009

Unit Testing != Test-Driven Development

Unit testing and test-driven development (TDD) are not equivalent.  With unit testing, you write tests that verify your code is functioning as expected.  This is often done after you have written the code itself.  With test-driven development, on the other hand, you write the tests before you’ve written any production code and use the tests to guide the design of your code.  Thus TDD is not just a way of testing; more importantly, it’s a design activity.

Just like other design activities, TDD is done before production code is written.  You first create a test (writing just enough production code to get the test to compile), run the test, and verify that it fails.  You next develop a solution and write production code that gets the failing test to pass.  Once the test is passing, you refactor and clean the code.  You then start the process over by creating another new test.  This cycle is known as “red-green-refactor”.

Writing your tests first forces you to think about requirements and how a user would interact with your API and classes before you even write any code.  You’re also focusing on writing small pieces of code that can be tested independently of other code, which leads to smaller classes that display high cohesion and low coupling.  Plus you’re incrementally adding tests and features, thereby providing you faster feedback and allowing you to learn more about the code than you would by writing all of the code first and then all of the unit tests afterwards. 

So while unit testing is a good practice, TDD is an even better one.

0 comments:

Post a Comment