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

后端 未结 3 445
暖寄归人
暖寄归人 2020-12-16 00:00

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

相关标签:
3条回答
  • 2020-12-16 00:02

    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)
    
    0 讨论(0)
  • 2020-12-16 00:07

    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.

    0 讨论(0)
  • 2020-12-16 00:13

    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")
    
    0 讨论(0)
提交回复
热议问题