JUnit Best Practices, Part 1 -- Don't Decide Anything
Creating JUnit tests can be something of a craft when you first start writing them. In our JUnit Best Practices articles, we hope to shed some light on what makes a good JUnit test, and why.
The purpose of a JUnit test is to set up a controlled environment in which the unit under test can be run. To that end, each JUnit test should be as logically simple as possible, preferably with no decisions at all.
Consider this JUnit test for a sample method called

If the
Adding decisions to your test methods only adds another variable to the test, which is exactly what you should avoid when unit testing. Keeping your unit tests decision-free will increase their effectiveness, clarity, and maintainability.
The purpose of a JUnit test is to set up a controlled environment in which the unit under test can be run. To that end, each JUnit test should be as logically simple as possible, preferably with no decisions at all.
Consider this JUnit test for a sample method called
countDuplicates():
If the
getTestInput() returns null, then countDuplicates() is never invoked. If you're looking at your testing status summary, this test will be marked as a success despite the fact that it didn't test anything! Of course, every rule has an exception, so if you absolutely must have decision logic in your test case, be extra diligent to make sure that your test fails if it doesn't execute as expected.Adding decisions to your test methods only adds another variable to the test, which is exactly what you should avoid when unit testing. Keeping your unit tests decision-free will increase their effectiveness, clarity, and maintainability.

0 Comments:
Post a Comment
<< Home