Tips on JUnit style

See also JUnit FAQ.

For novice testers

Each test MUST have an assert.  A method without an assert is not a test.

The convention for using JUnit asserts is that the first parameter is the EXPECTED result, and the second parameter is the actual result.

To make your intent clear, use assertEquals() when comparing results from a value-returning function. Use assertTrue() when verifying boolean functions.

Use the message argument so when your test fails it gives a meaningful message.  If you do this you don't have to include a comment explaining what the test does.

Keep tests independent of each other.  Ideally only one test should fail at a time.

Keep test methods small.  Purists argue that each test case has a single assert.  Pragmatists allow more than one assert as long as they all relate to testing the same behavior.

Avoid System.out and System.err in your tests.  Tests should be automated and not rely on visual inspection of output by a human tester.

Design your application in a manner that makes it easy to test. Separate your user interface classes from your business logic.  This will make the core logic easier to unit test, because the unit test doesn't require manual user input. 

Don't make your methods rely on System.in.  Instead pass in a Reader and create a Scanner from that.  Here's a demo project to illustrate the technique.

For Advanced testers

Create small, focused interfaces to your classes to make it easier to create and maintain "mock" implementations.

Avoid testing against databases and network resources (e.g. sockets).  Use an interface and a mock.

Add a main() method that runs the test in TestRunner.

Start by writing what you are testing: the assert.  Then work backward and fill in whatever is needed to set things up for the assert.

Always write a toString() method in the class being tested to improve failure reporting.

Create your test hierarchy around what the code does, not how it is structured.  Write tests for behaviors, not methods.  A test method should test a single behavior. 

Refactor your tests!  Avoid duplication of code in your tests as well as in the production code. 

TestCase is a mechanism for fixture reuse. So if you have a VideoList class, create separate TestCases for testing empty list behavior and testing full list behavior; TestEmptyList and TestFullList.  (You'll also want OneItemList and a FullMinusOneItemList test cases - boundary value analysis.)

Don't put tests in same folder has code being tested - put in a subpackage or parallel package.

Run a coverage tool often to see what you might be missing.

There should be at least as much test code as production code.  1.5 times as much is better.


See also the JUnit FAQ.