ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Best Practices for Exception Handling
Subject:   Exceptions in unit tests
Date:   2003-12-09 10:14:00
From:   zipwow
Response to: A few things

I felt the same way for a while, but also disliked the number of exception classes that were creeping into my API. Worse, it didn't completely solve the problem, as unless *every* throws clause was different, I could still get a false positive.


What I did was adopt this sentiment:


Every throws clause should construct its exception (of whatever type) with a different *message*. This is helpful anyway, since once I get an exception thrown, even if the code (like in production, say) doesn't keep line numbers, I know where it came from.


Then, in the unit test, I wrote code like this:


try {
makeUser("jimbob","easypassword");
fail("user creation should fail for dictionary password");
} catch (UserException e) {
assertTrue("MyException did not mention dictionary password",
e.getMessage().indexof(DICT_PASSWORD_STRING) != -1);
}


I'm not handling internationalization here, but if you are, I think there's an analagous solution, probably having to do with getMessage() vs getLocalizedMessage().


-Zipwow