How to unit or integration test use of injected messageSource for i18n in Grails 2.0 service

Peter picture Peter · Feb 3, 2012 · Viewed 9.6k times · Source

I make use of a message bundle in one of my services in a Grails 2.0 project for internationalized text. The use case is an email subject that is sent via the mail plugin in an asynchronous way, so it really doesn't make sense to have this in a controller or TagLib (given the usual argument of not accessing your text or views in a service). This code works fine in my running Grails app, but I'm not sure how to test it.

I tried a PluginAwareResourceBundleMessageSource in my defineBeans as that is what my running application injects, but it led to nullpointers as it appears it needs a bunch of setup around plugin managers and such that my test environment is not giving (even integration).

I then tried a ReloadableResourceBundleMessageSource as it was pure Spring, but it can't seem to see my .properties files, and fails with a No message found under code 'my.email.subject' for locale 'en'.

I feel like I'm going down a wormhole a bit as accessing Grails i18n in a service is not documented in the grails docs, so if there is a preferred way to do this, let me know.

Note my .properties file is in the standard grails-app/i18n location.

The test

@TestFor(EmailHelperService)
class EmailHelperServiceTests {

    void testSubjectsDefaultLocale() {
        defineBeans {
            //messageSource(PluginAwareResourceBundleMessageSource); Leads to nullpointers
            messageSource(ReloadableResourceBundleMessageSource);

        }
        String expected = "My Expected subject Passed1 Passed2";
        String actual = service.getEmailSubjectForStandardMustGiveGiftFromBusiness(Locale.ENGLISH, Passed1 Passed2);
        assertEquals("email subject", expected, actual);

}

Service:

    class EmailHelperService {
    def messageSource;

    public String getEmailSubject(Locale locale, String param1, String param2) {
        Object[] params = [param1, param2].toArray();      
        return messageSource.getMessage("my.email.subject", params, locale );      
    }

Answer

Graeme Rocher picture Graeme Rocher · Feb 4, 2012

There is already a messageSource in unit tests in Grails, it is a StaticMessageSource (see http://static.springsource.org/spring/docs/2.5.4/api/org/springframework/context/support/StaticMessageSource.html), you can add mock messages with the addMessage method:

messageSource.addMessage("foo.bar", request.locale, "My Message")