Grails 2.4.4控制器测试对save()返回空模型

时间:2015-06-05 00:00:37

标签: unit-testing grails

我对PersonController进行了测试,它只执行没有参数的save(),因此创建了一个无效的人。它应该返回模型中的无效人并显示创建视图。但模型是空的。

测试:

import org.junit.*
import grails.test.mixin.*

@TestFor(PersonController)
@Mock(Person)
class PersonControllerTests {
   ...
   void testSave() {
       controller.save() // creates invalid person, redirects to create
       assert model.personInstance != null
       assert view == '/person/create'

       response.reset()

       populateValidParams(params)
       controller.save()

       assert response.redirectedUrl == '/person/show/1'
       assert controller.flash.message != null
       assert Person.count() == 1
   }
   ...
}

控制器:

class PersonController {

   ...
    def save() {
        def personInstance = new Person(params)
        if (!personInstance.save(flush: true)) {
            render(view: "create", model: [personInstance: personInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'person.label', default: 'Person'), personInstance.id])
        redirect(action: "show", id: personInstance.id)
    }
   ...
}

输出:

junit.framework.AssertionFailedError: Assertion failed: 

assert model.personInstance != null
       |     |              |
       [:]   null           false

    at demographic.PersonControllerTests.testSave(PersonControllerTests.groovy:43)

如何获得正确的型号?

这是预期的行为还是Grails错误?

1 个答案:

答案 0 :(得分:1)

由于控制器中的HTTP方法限制,测试失败(我认为是正确的),即行:

static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

在测试中设置HTTP方法,测试通过:

void testSave() {
    controller.request.method = 'POST'
    controller.save() // creates invalid person, redirects to create
    ...