Grails控制器测试中的模型为空/空

时间:2014-08-21 17:56:36

标签: grails spock

我最近在一个非常大的应用程序中创建了一个新的控制器(注意:我们刚刚从Grails 2.0.3升级到2.3.7)并且所创建的测试都已经莫名其妙地失败了。我的大部分错误都是在控制器调用后模型为[:]。因此该模型上的任何方法都为null。我得到的东西是:

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

但测试通过了。这只发生在create上。发生了什么事?

编辑:添加用于创建和保存的代码

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。我会抛弃命令创建的测试并从头开始,感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,但解决方法如下:

控制器方法内部:

 render view: "_myTemplate", model: [instance: myInstance]

所以控制器仍然呈现模板,在测试规范中我可以测试

assert(model.instance = myExpectedInstance)