So originally we used a StaticMessageSource approach where we created a message source with all the appropriate codes and then tested against it. That became a pain to maintain and so I took an alternate approach:
Write your own testMessageSource. Mine looks like this:
Code:
public class TestMessageSource extends AbstractMessageSource {
/**
* Resolve code returns a message with the code and ignores Locale
* @param code
* @param locale
* @return
*/
protected MessageFormat resolveCode(String code, Locale locale) {
return createMessageFormat(code, locale);
}
}
If you use this as your message source, it will always insert a message with the code itself as teh message. So you can do things like:
Code:
public void testPhaseIsBlank() throws Exception {
TestMessageSource source = new TestMessageSource();
DefaultMessageContext ctx = new DefaultMessageContext(source);
EditForm epf = new EditForm();
epf.setPhase(null);
epf.validateSave(ctx);
assertMessageExists("editForm.noPhase", ctx);
}
public static void assertMessageExists(String msg, MessageContext msgs) {
for (Message message : msgs.getAllMessages()) {
if (message.getText().contains(msg)) {
return;
}
}
Assert.fail("msg '" + msg + "' not found in msgs: " + msgs);
}
Obviously, this doesn't test that your messages resource contains the right codes but that's a much more complicated issue (because some messagebuilders might specify default messages, etc.). We actually solve that by code analysis (ie, look for all messagebuilders, find all message codes, make sure they are in the resource file) rather than testing.
Hope this helps!