Good error messages are a cornerstone of any useable software tool, but automated testing of error messages can be a challenge. Using the exception message is not usually appropriate, as it can change through internationalization or an exception that only provides formatted messages.The way that I've attacked this sort of thing in the past is to use what could be called keyed exceptions. That is, a class that looks like:public class MyException extends Exception { public static final short STUPID_ERROR = 0; public short _key; public MyException(short key) {
super();
_key = key;
} public getKey() {
return _key;
}
}with a few other constructors if need be (e.g., with a message or nested exception) and some additional keys. When the exception is constructed and thrown from code, it should be supplied with the appropriate key:throw new MyException(MyException.STUPID_ERROR)And then in a unit test, you can have:try {
doSomethingWrong();
fail("Should have thrown MyException.");
} catch (MyException me) {
assertTrue(
"Should have had key=" + expectedValue,
me.getKey() == expectedValue);
}There are then ways to make this fancier to handle things like line numbers, file names, and other metadata about an exception in a checkable way.