gpt4 book ai didi

unit-testing - 在使用Grails 2.5.1的Spock单元测试中, Controller 始终为null

转载 作者:行者123 更新时间:2023-12-02 14:30:22 26 4
gpt4 key购买 nike

我是使用Grails 2.5.1的新手。我需要运行一些单元和集成测试,但无法使其正常运行。

我的域类是:

class Role {

String roleName

Role(String _roleName) {
roleName = _roleName
}

static constraints = {
roleName(blank: false, nullable: false)
}
String toString(){
"$roleName"
}

}

我的 Controller 类是:
class RoleController {

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

def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond Role.list(params), model:[roleInstanceCount: Role.count()]
}

def show(Role roleInstance) {
respond roleInstance
}

def create() {
respond new Role(params)
}

...
}

在测试/单元下,我有类RoleControllerSpec:
import grails.test.mixin.*
import spock.lang.*

@TestFor(RoleController)
@Mock(Role)
class RoleControllerSpec extends Specification {

def 'index action: 1 role'() {
setup:
roleInstance.save()

expect:
controller.index() == [roleInstanceList: [roleInstance], roleInstanceTotal: 1]

where:
roleInstance = new Role(roleName: "Role1")
}



def "create action"() {
setup:
controller.params.roleName = roleName

when:

def model = controller.create()

then:
model.roleInstance != null
model.roleInstance.roleName == roleName


where:
roleName = "Role1"

}
}

当我使用test-app -unit RoleController运行测试时,出现以下异常:
|Configuring classpath
.
|Environment set to test
....................................
|Running without daemon...
..........................................
|Compiling 1 source files
.
|Running 2 unit tests...

|Running 2 unit tests... 1 of 2
Failure: |
index action: 1 role(accessmanagement.RoleControllerSpec)
|
Condition not satisfied:
controller.index() == [roleInstanceList: [roleInstance], roleInstanceTotal: 1]
| | | |
| null false Role1
role(RoleControllerSpec.groovy:17)

|Running 2 unit tests... 2 of 2
Failure: |
create action(accessmanagement.RoleControllerSpec)
|
java.lang.NullPointerException: Cannot get property 'roleInstance' on null object
at accessmanagement.RoleControllerSpec.create action(RoleControllerSpec.groovy:34)

|Completed 2 unit tests, 2 failed in 0m 6s
.Tests FAILED
|
Error |
Forked Grails VM exited with error

在我的测试中, Controller 似乎为空。
在第一个测试中controller.index()为null。在第二个测试中,def model = controller.create()未创建对象,然后当我尝试访问model.roleInstance时无法获取该属性。

任何想法将不胜感激。
谢谢!

最佳答案

由于您使用的是响应而不是简单地从 Controller 返回映射,因此您需要检查model属性

def 'index action: 1 role'() {
setup:
Role roleInstance = new Role(roleName: "Role1").save()

when:
controller.index()

then:
model == [roleInstanceList: [roleInstance], roleInstanceTotal: 1]
}

我建议您阅读有关测试 Controller https://grails.github.io/grails-doc/2.5.x/guide/testing.html#unitTestingControllers的文档

关于unit-testing - 在使用Grails 2.5.1的Spock单元测试中, Controller 始终为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120133/

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