JUnit Best Practices, Part 2 -- Keep 'em Separated
A common practice for those new to JUnit is to try and cover more ground with fewer tests. As long as you're writing your
Wrong. Not only should a unit test focus on one specific unit, it should focus on one specific behavior of that unit. Testing multiple behaviors at once only muddies the water. Consider our hypothetical

Now suppose the assertion fails. Which of the two
One exception to the rule here is that sometimes you may need to invoke your method under test multiple times in order put things in a particular state before performing the actual test of your method. In such cases, consider using a mock object to prepare the test state in a controlled fashion. The net result is the same -- the only variable in your test is the one behavior that you're testing.
Testing many different behaviors in a single test method is a common practice because it's so easy to do, but this is a clear case of being penny-wise and pound-foolish. Take the time to separate each behavior into its own unit test.
testAdd() unit test, you may as well invoke add() as many different ways as possible and see what breaks, right? Wrong. Not only should a unit test focus on one specific unit, it should focus on one specific behavior of that unit. Testing multiple behaviors at once only muddies the water. Consider our hypothetical
testAdd() method:
Now suppose the assertion fails. Which of the two
add() invocations returned the wrong value? You won't know until you start digging. The purpose of unit testing is to take the guesswork out of error location, and this technique defeats that purpose.One exception to the rule here is that sometimes you may need to invoke your method under test multiple times in order put things in a particular state before performing the actual test of your method. In such cases, consider using a mock object to prepare the test state in a controlled fashion. The net result is the same -- the only variable in your test is the one behavior that you're testing.
Testing many different behaviors in a single test method is a common practice because it's so easy to do, but this is a clear case of being penny-wise and pound-foolish. Take the time to separate each behavior into its own unit test.





