Thursday, January 22, 2009

Where to place Unit Test source

A subject of some debate around our shop lately is where unit test source should be kept relative to production source.

One camp believes the habits evident in tools like Eclipse and Maven where unit test code is in a completely separate directory than your application source is best.

I'm favoring the opinion that keeping the test source in the same location as the production code is preferable.

My primary reasons include:

- forcing the tests to be seen as first class elements. Not relegated to a special case.
- makes it impossible for someone to compile source from IDE and NOT compile the tests along with. (reduces broken builds)
- when viewing source by path, makes tests proximate and conveniently right next to the classes they test.
- supports refactoring. When you move a class due to refactoring it's all but impossible to forget to move the test along with it.

The drawbacks include:

- Some tools like Maven's default script and the create test features in IDEs like Eclipse assume a separate Test directory.

- The release build script needs to explicitly exclude the tests from compile.

Neither of these are significant to me relative to the benefits. Tweaking the build scripts for release targets to exclude test classes is trivial and the convienience tools to create tests in IDEs are rather anti-TDD in that they assume you have a class first to generate test from. Test infected devs should be creating test classes BEFORE the prod class anyway.

Here are a few links to others who have grappled with this question:

Project directory structure that facilitates all kinds of developer testing (Testing forum at JavaRanch): "functional"

Unit Testing Guidelines