unit-testing - 在save()上的Grails 2.4.4 Controller 测试返回空模型

标签 unit-testing grails

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

考试:

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
   }
   ...
}

Controller :
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的错误?

最佳答案

由于 Controller 中的HTTP方法限制(即该行),测试失败(正确的是,我相信是这样):

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

在测试中设置HTTP方法,测试通过:
void testSave() {
    controller.request.method = 'POST'
    controller.save() // creates invalid person, redirects to create
    ...

关于unit-testing - 在save()上的Grails 2.4.4 Controller 测试返回空模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30656191/

相关文章:

grails - 如何编写Grails过滤器的集成测试

grails - 向 grails 中的所有 View 添加变量

java - Spring Boot 多模块测试

python - 如何将测试名称和模块添加到结果中的测试文档字符串?

unit-testing - 如何从 TFS 2015 中的单元测试中获取调试输出

grails - 用于Grails的JasperReports插件:获取 “No such report spec”异常

grails - Grails:在 Controller 中动态更改域的约束

tomcat - 为什么 Grail App war 文件与源代码相比体积太大

amazon-web-services - 如何为 Go 调用模拟 AWS SDK

python - 在 SQLAlchemy 应用程序的单元测试中使用 Alembic?