gpt4 book ai didi

unit-testing - 测试 grails 数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 04:17:03 26 4
gpt4 key购买 nike

我编写了以下 Grails Controller

class CategoryController {

def create = {
def newCategory = new CategoryCommand()
bindData(newCategory, params)
[newCategory: newCategory]
}
}

class CategoryCommand {

String name
String seoName
}

我编写了这个单元测试来测试数据绑定(bind):
class CategoryControllerTests extends ControllerUnitTestCase {


void testCreate() {

// A new ControllerCommand should be returned if invoked with no params
assertNotNull controller.create()

// If called with params, they should be bound
mockParams.name = 'snooker'
mockParams.seoName = 'snooker-loopy'
def model = controller.create()

CategoryCommand newCategory = model.newCategory
assertEquals 'snooker', newCategory.name
assertEquals 'snooker-loopy', newCategory.seoName

}
}

但是当 controller.create() 时出现此异常被调用:

No signature of method: com.example.CategoryController.bindData() is applicable for argument types: (com.example.CategoryCommand, org.codehaus.groovy.grails.web.taglib.GroovyPageAttributes) values: [com.example.CategoryCommand@7860e7d2, [:]]



我尝试将其作为集成测试运行,但结果是相同的。

最佳答案

对...我挖了一下,发现this blog page它说(大约一半):

note:ControllerUnitTestCase not support some dynamic method. For instance: bindData(). Then is better use integration testing, or you can add this method to controller:


this.controller.metaClass.bindData = { obj, params ->  
params.each { key, value ->
obj."$key" = value
}
}

或者,我查看了 Grails source code ,并模拟它做同样的事情 as what Grails does ,我认为你需要这样做:
import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod

this.controller.metaClass.bindData = { obj, params ->
new BindDynamicMethod().invoke( delegate, BindDynamicMethod.BIND_DATA_METHOD, [ obj, params ] as Object[] ) ;
}

(我认为 - 没有测试过)

关于unit-testing - 测试 grails 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5351704/

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