Wednesday, June 11, 2008

Test Driven Development

Test Driven Development is normally when you write tests, and then write code to make those test pass.

I find that a good way to start out with test driven development is to modify it slightly. Instead of writing the test first, write the method. Then immediately write the test. Often people new to TDD take a while to learn how to write tests and having the method under test helps with the process of learning to write tests.

The first tool that you need to learn is JUnit. JUnit allows you to quickly write tests to exercise your code, espically JUnit 4 introduced annotation based tests, which makes writing tests very easy.

The next tool you should look at is a mock object package. I personally use jMock, but other people swear by easyMock. Mock objects let you isolate an object under test. The key to being able to use mock objects is to decouple your dependencies.

I personally prefer using dependency injection to decouple your dependenices. Martin Fowler has a good overview of the subject on his website.

How much of your development time should be spent writting unit tests? In general, I find that a good rule of thumb is that about 50% of your development time should be on unit tests and 50% on production code.

TDD tends to produce better production code. In order to make the production code testable, you wind up writing code with a lower cyclomatic complexity, thus tending to have fewer bugs in your code to begin with.
TDD gives you good unit test coverage. You should have test for each method, most likely you'll have more than one test for each method, ideally you should have at least the cyclomatic complexity number of tests.
Due to the good test coverage, you can refactor with confidence that you will detect very quickly if you do break code.

Give it a try, it may take a while to get used to, but once you do, you'll be happy you did.

No comments: