15 Best Practices for Unit Testing Your Java Code Using Junit

Disclaim and Credit:

The exerpt is from a book Java Development with Ant, by Erik Hatcher and Steve Loughran, published by Manning Publications Company. The credit goes to the authors of the book and the publishers.

The following are the best practices for unit testing.

  1. Test everything that could possibly break. This is an XP maxim and it holds.
  2. A well-written test is hard to pass. If all your tests pass the first time, you are probably not testing vigorously enough.
  3. Add a new test case for every bug you find.
  4. When a test case fails, track down the problem by writing more tests, before going to the debugger. The more tests you have, the better.
  5. Test invalid parameters to every method, rather than just valid data. Robust software needs to recognize and handle invalid data, and the tests that pass using incorrect data are often the most informative.
  6. Clear previous test results before running new tests; delete and recreate the test results and reports directories.
  7. Set haltonfailure=”false” on to allow reporting or other steps to occur before the build fails. Capture the failure/error status in a single Ant property using errorProperty and failureProperty.
  8. Pick a unique naming convention for test cases: *Test.java. Then you can use with Ant’s pattern matching facility to run only the files that
    match the naming convention. This helps you avoid attempting to run helper or base classes.
  9. Separate test code from production code. Give them each their own unique directory tree with the same package naming structure. This lets tests live in the same package as the objects they test, while still keeping them separate during a build.
  10. Capture results using the XML formatter: .
  11. Use , which generates fantastic color enhanced reports to quickly access detailed failure information.
  12. Fail the build if an error or failure occurred:
  13. Use informative names for tests. It is better to know that testDocumentLoad failed, rather than test17 failed, especially when the test suddenly breaks four months after someone in the team wrote it.
  14. Try to test only one thing per test method. If testDocumentLoad fails and this test method contains only one possible point of failure, it is easier to track down the bug than to try and find out which one line out of twenty the failure occurred on.
  15. Utilize the testing up-to-date technique. Design builds to work as subcomponents, and be sensitive to build inefficiencies doing unnecessary work.
Tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *