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

耗尽温柔 提交于 2019-11-29 01:35:26

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")

In unit tests and the local side of functional tests, sometimes you want the real properties that are in the 18n directory.

This works for me:

  MessageSource getI18n() {
    // assuming the test cwd is the project dir (where application.properties is)
    URL url = new File('grails-app/i18n').toURI().toURL()
    def messageSource = new ResourceBundleMessageSource()
    messageSource.bundleClassLoader = new URLClassLoader(url)
    messageSource.basename = 'messages'
    messageSource
  }

  i18n.getMessage(key, params, locale)

In a unit test you could ensure that you're wired up correctly by doing something like this:

void testSubjectsDefaultLocale() {
    def messageSource = new Object()
    messageSource.metaClass.getMessage = {subject, params, locale ->
        assert "my.email.subject" == subject
        assert ["Passed1", "Passed2"] == params 
        assert Locale.ENGLISH == locale
        "It Worked!!!"
    }
    service.messageSource = messageSource
    String actual = service.getEmailSubjectForStandardMustGiveGiftFromBusiness(Locale.ENGLISH, Passed1 Passed2)
    assert "It Worked!!!" == actual
}

This will help ensure that you're wired up correctly but it will not ensure that what you're doing actually works. If you're comfortable with that then this would work for you. If you're trying to test that when you give "XYZ" to your .properties file it returns "Hello" then this will not work for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!