【发布时间】:2014-08-21 17:56:35
【问题描述】:
我最近在一个相当大的应用程序中创建了一个新控制器,(注意:我们刚刚从 Grails 2.0.3 升级到 2.3.7)并且创建的测试都莫名其妙地失败了。我的大部分错误都包括模型在控制器调用之后是 [:] 。因此,该模型上的任何方法都为空。我得到类似的东西:
groovy.lang.MissingMethodException:
No signature of method:
TransitionController.save() is applicable for argument types: (Transition)
values: [null] Possible solutions: save(), wait(), show(), any(),
wait(long), raw(java.lang.Object) at TransitionControllerSpec.Test the
save action correctly persists an instance(TransitionControllerSpec.groovy:45)
我已经尝试通过以下方式明确分配模型:
def model = controller.delete()
def model = controller.update()
//....
但是如果我尝试访问它,我会得到相同的结果,一个空的模型映射和空值。 根据这篇文章 (https://jira.grails.org/browse/GRAILS-8462),我还可以尝试通过以下方式访问模型:
def model = controller.modelAndView.model
但这对我也不起作用,产生了相同的结果。
对可能发生的事情有任何想法吗?
编辑:这是前几个测试
package com.hey.how.are.ya
import grails.test.mixin.*
import spock.lang.*
import org.junit.*
@TestFor(TransitionController)
@Mock(Transition)
class TransitionControllerSpec extends Specification {
def populateValidParams(params) {
assert params != null
params['reason'] = 'just cuz'
}
void "Test the index action returns the correct model"() {
when:"The index action is executed"
controller.index()
then:"The model is correct"
!model.transitionInstanceList
model.transitionInstanceCount == 0
}
void "Test the create action returns the correct model"() {
when:"The create action is executed"
controller.create()
then:"The model is correctly created"
model.transitionInstance!= null
}
//...grails generated tests here
}
编辑:这是一个有趣的案例!如果我这样做:
void "Test the create action returns the correct model"() {
when:"The create action is executed"
def model = controller.create()
def inst = new Transition()
println "${model}"
println "${model.transitionInstance}"
then:"The model is correctly created"
model.transitionInstance != null
}
然后我得到这个作为输出:
[transitionInstance:null]
null
但是测试通过了。这只发生在创建。怎么回事??
编辑:添加用于创建和保存的代码
def create() {
[transitionInstance: new Transition(params)]
}
def save() {
def transitionInstance = new Transition(params)
if (!transitionInstance.save(flush: true)) {
render(view: "create", model: transitionInstance: transitionInstance])
return
}
flash.message = message(code: 'default.created.message', args: [message(code: 'transition.label', default: 'Transition'), transitionInstance.id])
redirect(action: "show", id: transitionInstance.id)
}
编辑:我不能在这上面花太多时间,但我很确定问题是生成的控制器和创建的测试之间存在差异。值得一提的是,我正在运行 2.0.2 版的脚手架插件和 grails 2.3.7。我将丢弃命令创建的测试并从头开始,感谢您的帮助!
【问题讨论】:
-
你能展示一个完整的测试吗?通常,如果您使用 @TestFor 注释,您将从 mixin 中获得
model和view变量。 -
我添加了前几个测试和我的导入。我同意注释测试应该让我得到模型。
-
您能否将
save方法以及save方法本身的测试添加到帖子中?因为错误消息与您显示的测试不对应。 -
我在 v2.4.4 上遇到了同样的问题。