Writing Java Unit Tests

What basic principles should I follow in creating tests?

Ignoring the whole CodeUnitTestFirst issue, you should create tests in small chunks. Have each test method test only one piece of functionality (You will often need to use other functionality to set up the test, but that individual test should assume that those worked).

Because a test stops executing when an assertion fails, don't put unrelated assertions into the same test method. Make a new test method, and extract out any common setup code either to the setUp() helper method or another method that both tests invoke.

Don't bother putting a lot of diagnostic support into your test case to work out exactly why something has broken; the first time the test case breaks and you need to figure out why (as opposed to knowing it because you're working on that feature), you can do it then. YAGNI applies here, just as everywhere else.

Your tests should be environment-independent; they shouldn't break when somebody runs them on a box other than yours. Use JavasTempFileFacility. Load test data files as resources.

Remember: TestEverythingThatCouldPossiblyBreak. Oh, and CodeUnitTestFirst.


There is a fairly good article on the JavaUnit site, which is referenced in TestInfected.


EditText of this page (last edited May 29, 2002) or FindPage with title or text search