测试控制器中的MessageSource实例(调用调用MessageSource的服务。)

时间:2016-03-22 15:40:25

标签: grails spock

我正在使用grails 2.3.6而我正在尝试测试一个调用一个调用MessageSource的服务的控制器。我已经尝试过这篇文章中的所有解决方案(How to unit or integration test use of injected messageSource for i18n in Grails 2.0 service),但我仍然收到此错误:

org.springframework.context.NoSuchMessageException: No message found under code 'enrolment.state.approved' for locale 'es_ES'.
    at es.portel.accessRequest.enyca.EnrolmentClientService.enrolmentTranslateState(EnrolmentClientService.groovy:30)
    at es.portel.accessRequest.enyca.EnrolmentClientService.enromentsTranslateState_closure1(EnrolmentClientService.groovy:13)
    at es.portel.accessRequest.enyca.EnrolmentClientService.enromentsTranslateState(EnrolmentClientService.groovy:12)
    at es.portel.accessRequest.enyca.EnrolmentClientController.getAllEnrolments(EnrolmentClientController.groovy:41)
    at es.portel.accessRequest.enyca.EnrolmentClientControllerSpec.test getAllEnrolments method(EnrolmentClientControllerSpec.groovy:34)

这是我的测试代码:

@TestFor(EnrolmentClientController)
 @Mock(EnrolmentClientService)
 class EnrolmentClientControllerSpec extends Specification{
    void "test getAllEnrolments method"() {
       given:
       MessageSource messageSource = getMessageSource()
       controller.enrolmentClientService = new EnrolmentClientService()
       controller.enrolmentClientService.messageSource = messageSource
       Locale locale1 = new Locale("es_ES")
       messageSource.addMessage('enrolment.state.approved',locale1, 'Aprobado')

       when:
       controller.getAllEnrolments()

       then:
       assertEquals response.status,  HttpServletResponse.SC_OK
       assertEquals response.format, 'json'
       }
   }

任何想法? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

经过几次头痛,我终于解决了。我脱掉了模拟服务,因为看到303告诉我并进行了适当的设置。这是工作代码:

@TestFor(EnrolmentClientController)
class EnrolmentClientControllerSpec extends Specification {
    @Shared
    def messageSource = new StaticMessageSource()

    def setupSpec() {
        Locale locale1 = new Locale("es_ES")
        messageSource.useCodeAsDefaultMessage = true
        messageSource.addMessage "enrolment.state.approved", locale1, "Aprobado"
    }


    void "test getAllEnrolments method"() {
       given:
       controller.enrolmentClientService = new EnrolmentClientService()
       controller.enrolmentClientService.messageSource = messageSource

       when:
       request.method = 'GET'
       response.format = 'json'
       controller.getAllEnrolments()
    }
}