I am big fun of Test Driven Development (TDD). I recently read quite good article about unit testing: Write Maintainable Unit Tests That Will Save You Time And Tears. Here is an extract of the article:
- Fail First (before you write piece of logic, write fail test first) - do not write any test, but simulate production environment that will use the logic so the test will remain as regression test of your logic.
- Requirements conflict (old UT fails when new funct. is introduced) - remove or enhance old UT.
- If you can remove a line in your tested class and all tests still pass - you have not enough unit tests.
- Remeber that tests must be maintained as any other code - so 'Keep It Simple, Stupid' (KISS)
- Make tests easy to run (or at least some subset of tests) so developers can run it often.
- Do not let peaple to stop trust the tests - the less false-positives in failed tests the better.
- Test only public interface of component.
- Reuse your creation, manipulation, and assertion code when possible.
- Don't create instances of classes directly inside a unit test - use factory even more than normally.
- Refactor unit tests - mainly to KISS them .
- Avoid dependencies between tests - any test should work run in any order .
- Create readable tests - write comments in Asserts and in UT. Write descriptive method names (even very long). Use local variables in Asserts. Use constants. UT should be readable like a book.
Here is an extract of one of many UT articles. I would like to create some check list to be able to do code review of unit tests based on the list and on the principles contained in it.