简体   繁体   English

如何单元测试grails的消息标记

[英]how to unit test grails' message tag

in the controller there is an action: 在控制器中有一个动作:

    def delete = {
    withDomain {
        it.delete()
        flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'chocolateBar.label', default: 'ChocolateBar'), it.name])}"
        redirect action: 'list'
    }
}

which can be tested in development. 可以在开发中测试。 while in unit test , the message(..) method throws exception ( groovy.lang.MissingMethodException: No signature of method: longtest.ChocolateBarController.message() is applicable for argument types: (java.util.LinkedHashMap) values: [[code:chocolateBar.label, default:ChocolateBar]]): 单元测试中 ,message(..)方法抛出异常(groovy.lang.MissingMethodException:没有方法签名:longtest.ChocolateBarController.message()适用于参数类型:(java.util.LinkedHashMap)值:[[ code:chocolateBar.label,默认:ChocolateBar]]):

    public void testDelete() {
    controller.params.id = '3'
    controller.delete()
    assert 'list'==controller.redirectArgs.action
}

After study, a mockTagLib method should be called during setup. 研究之后,应该在安装过程中调用mockTagLib方法。 But found no correct class name for built-in message(..). 但是没有找到内置消息(..)的正确类名。 Please help. 请帮忙。

I've solved the problem in unit controller test. 我已经解决了单元控制器测试中的问题。 like this: 像这样:

//This is inside Spock test

@Shared
ResourceBundleMessageSource messageSource = null

@Shared
Closure mockMessage = {Map map ->
    return messageSource.getMessage((String)map.code, (Object[])map.args, Locale.default)
}

def setupSpec(){
    URL url = new File('grails-app/i18n').toURI().toURL()
    messageSource = new ResourceBundleMessageSource()
    messageSource.bundleClassLoader = new URLClassLoader(url)
    messageSource.basename = 'messages'
    messageSource.setDefaultEncoding("utf-8")
}

def setup(){
    controller.metaClass.message = mockMessage
}

This code is for spock test, but main idea is also available for normal grails test. 此代码用于spock测试,但主要思路也可用于正常的grails测试。
In running phase(not test), 在运行阶段(不是测试),
calling "message" in controller class results in calling "message" of ValidationTagLib class, 在控制器类中调用“message”会导致调用ValidationTagLib类的“message”,
but they are not bind in unit test phase. 但它们在单元测试阶段没有约束力。
So I made almost same logic of "message" of ValidationTagLib, 所以我对ValidationTagLib的“消息”做了几乎相同的逻辑,
and bind it(named "mockMessage") to controller.message. 并将它(名为“mockMessage”)绑定到controller.message。
With this code, you can execute "message" correctly in controller class in test. 使用此代码,您可以在测试中的控制器类中正确执行“消息”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM