Re: a junit question: how to catch an Exception from a test case?
On Fri, 10 Apr 2009, www wrote:
I did my original posting based on my previous experience. I cannot
reproduce the my observation now. I remember the error information lead
me to no-where. It took me a while to realize that an Exception was
thrown. Maybe my example code is not right.
I have reproduced the problem. I was not lying.
So you claim. :)
The problem comes from tearDown() and my example code was not right. The
code reproducing my observation is:
public void testMethodA() throws Exception
runMethodA(); //this method has a clause "throws Exception"
public void tearDown()
You're doing it wrong. tearDown is not the place to be doing assertions -
you do the assertions in your test methods and just do cleanup in
When runMethodA() throws an Exception, the flow still comes to
tearDown(), then it cannot find the generated_file because runMethodA()
didn't generate it. The junit message (I am using Eclipse) says
junit.framework.AssertionFailedError, nothing else. The console error
message says that it cannot find the file. No any information about
Exception and where the code caused the Exception.
Right, because tearDown is not somewhere that 'interesting' exceptions are
supposed to happen. If something goes wrong in tearDown, junit/Eclipse
notes it, to tell you that something went wrong, but doesn't give you the
details, because it's not a test failure.
BTW, I don't want to move the verification code from tearDown() to
individual junit test case, because I have several junit test cases. The
code will be repeated that many times.
In that case, you may be interested in a facility java has called 'method
calls'. You may have heard of them before. Factor the checking code out
into a validateGeneratedFile method, and put a call to that at the end of
each test method.
secular utopianism is based on a belief in an unstoppable human ability
to make a better world -- Rt Rev Tom Wright