Alex Rivera | Logout

JUnit test — analysing expected Exceptions

Asked 2010-12-20T12:56:45.173
44

In JUnit, I'm currently using annotation to expect an exception in my tests.

Is there a way to analyse this exception? For example, I expect a CriticalServerException, but I also want to verify the content of the getMessage method.

Edit
Report

1 Answer

21

I'm not sure if you should. Using a try-catch block to check the error message is so junit3ish. We have this cool feature now that you can write @Test(expected=CriticalServerException.class) and you want to go "back" and use try-catch again to fetch an exception you expect, just for checking the error message?

IMO you should stay for the @Test(expected=CriticalServerException.class) annotation and ignore the error message. Checking the error message, which can be changed a lot as it is a more "human readable" string and not a technical value, can also be tricky. You are forcing the exception to have a specific error message, but you might not know who generated the exception and what error message he chose.

In general you want to test if the method throws the exception or not, and not what the actual error message looks like. If the error message is really so important you should maybe consider using a subclass of the exception it throws and check it in @Test(expected=...).

answered 2010-12-20T13:13:56.327

Your Answer