Normally, when you run a junit test and it has an error, you look at the error and it helps you figure out what’s wrong. But I encountered a situation today that was a layer deeper:
Here’s what we saw:
A NullPointerException in the tearDown method (technically, in the @After method since we’re using JUnit 4). The error didn’t give much clue as to what the cause was.
What happens in cases like this is that when the @After method causes an exception, that exception masks any previous exception that the @Before method or @Test method may have experienced.
To diagnose the problem, we comment out the contents of the @After method for the moment and then run the test again (maybe just running one test method (you can do this by opening the class in Eclipse’s Outline view, then right-clicking on one of the methods and Run As… JUnit Test) to avoid accumulating a bunch of gunk that the @After method would have cleaned up if it weren’t commented out). Now that we had removed the masking exception, the stack trace showed clearly what the problem was (in our case, there were some properties that needed to be set in a properties file).