gpt4 book ai didi

unit-testing - 单元测试 grails 中的嵌套命令对象

转载 作者:行者123 更新时间:2023-12-02 14:07:57 25 4
gpt4 key购买 nike

文档说我们可以通过模拟参数来测试带有命令对象的 Controller
http://grails.org/doc/latest/guide/testing.html#unitTestingControllers

我想知道这是否适用于嵌套命令对象?有没有人让这个工作?

例子:

Controller

def create(FormCommand form){
form.validate()
...
}

命令
class FormCommand {
InnerCommand cmd
}

class InnerCommand{
String x
static constraints ={
x(nullable: false)
}
}

测试
void testCreate(){
params["inner.x"]="any"
controller.create()
...
}

我的期望是命令对象被创建并且数据绑定(bind)工作,我也期望内部命令被验证。我期待太多了吗?

最佳答案

好的,这似乎是您想要的,但需要一些代码:-)

数据绑定(bind)

对于嵌套命令对象,Grails 数据绑定(bind)需要内部命令的非空实例。

为此,您可以创建自定义 org.codehaus.groovy.grails.web.binding.BindEventListener :

class InnerCommandBindEventListener împlements BindEventListener {
public void doBind(Object target, MutablePropertyValues source, TypeConverter typeConverter) {
target.cmd = new InnerCommand()
}
}

并在您的 中声明资源.groovy
innerCommandBindEventListener(InnerCommandBindEventListener)

嵌套验证

要解决验证问题,您需要为您的 cmd 自定义验证器:
class FormCommand {
InnerCommand cmd
static constraints = {
cmd nullable: false, validator: { cmd, obj ->
// manually trigger the inner command validation
if(!cmd.validate()) {
return 'invalid.innercommand.message'
}
}
}
}

关于unit-testing - 单元测试 grails 中的嵌套命令对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15823362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com