Tuesday, October 15, 2013

Testing locale-specific code without wiring up a Spring MessageSource

Today I needed to create a JUnit test for a validator class that was using a MessageSource to retrieve the message content I was sending back to the user. When I first ran my unit test, of course the message source was null. I was left wondering if I was going to have to create a test context XML file just to wire up the test (cries in the fetal position under desk).

Instead, I found an easier answer - Spring's StaticMessageSource implementation. You can create an instance of this class, and add messages to it (code, locale and message):

StaticMessageSource messageSource = new StaticMessageSource();
messageSource.addMessage("my.message.path", Locale.US, "My Message");


With this solution, I was able to unit test my validator code with needing to wire up the actual MessageSource implementation. Obviously this solution will not work if you're testing/validating the actual message content.

No comments:

Post a Comment