I like to say that a good programmer is one who knows how to write good unit tests.
A good unit test grants that tested code is correct, testable, readable, reasonable and even elegant!
So how to write good unit tests?
This is my personal best practices list:
- always use tdd: it grants that the interfaces of your classes (i.e. your api) are created in a real life scenario; testability improves code readability and inner structure, giving it a simple design
- use data builders: tests require to create many objects; use data builders to build them; style your test building code defining your own dsl for data building
- don't use db-unit, use db builders: db-unit context files are external to the tests, making them less readable and self-contained; these files duplicate code and are hard refactor and maintain (does eclipse refactor automatically an xml/excel ?); so apply the builder pattern to create db objects in java too
- use light-weight mock: don't try to verify the internal behaviour of a mock, just mock its external behaviour; digging into the internals of a mock exposes to much information making the test fragile; most of the time you can check the correctness of the class under test just by checking it externally (by the way my favourite mocking library is mockito)
- write readable asserts: use a matcher library such as hamcrest or a dsl like fest-test
- use dsl when possible: there are nice libraries out there (time4tea, fest-reflect) that can make your test (or actual) code more fluent, and you can easily create your own (i did a small one for date manipulation, maybe i will post it later on)
So go unit testing right now :)