I have a simple test set up in JUnit, along the lines of
public void testGetBar() throws MyException{
Foo f = new Foo();
f.setup();
assertEquals(new Bar("1234"), f.getBar());
}
Suppose getBar()
threw a MyException
: JUnit notes this as a test "in error", and I notice that I screwed up the method. Yay, unit testing works! However, I have no way of knowing what was wrong with my Foo object that made it throw when I tried to getBar()
on it, without going back and e.g. running the test through a debugger, or adding a logging statement. Everybody says it's a bad idea catch exceptions in your JUnit tests, so it seems hamfisted to do this:
try{
assertEquals(new Bar("1234"), f.getBar());
} catch(MyException e) {
log.error(f.toString());
throw e;
}
but it's all I can think of. Is there no JUnit-y shorthand of saying "when there's an exception in this test, log out this, that, and the other object state (somehow)"开发者_如何学运维 to make it easy to figure out where things went wrong?
You should improve the quality of information in the exceptions you throw so that you can understand what went wrong in the unit test. This ensures that later if an exception is thrown in production you will have a useful exception message rather than something cryptic.
I'm not sure why you want to conditionally log exceptions. A unit test should always pass or always throw an exception. If you want to expect an Exception add the Annotation @Test(expection=Exception.class)
If you really want to log exceptions the most elegant way is to annotate your test class with @RunWith(MyRunner.class)
and create a class MyRunner extends BlockJUnit4Runner
that handles the logging.
You wouldn't wrap all your unit testing code in exception handlers: just the ones your having trouble with. Leaving JUnit to catch unanticipated exceptions as errors is also fine: wrap the offending code in a handler when that happens and you're investigating the problem (then remove again).
This should all be fairly infrequent though: you don't want code that throws random exceptions when you're unit testing (which should be as clean and repeatable as possible).
Of course, you will want to unit test your exception generation too: in which case you will definitely want to wrap the call to the offending function in a handler, then throw a fail() if the exception does not occur.
精彩评论