在使用Grails 2.5.1的Spock单元测试中,控制器始终为空

时间:2015-12-06 16:59:40

标签: unit-testing grails spock

我是Grails 2.5.1的新手。我需要运行一些单元和集成测试,但我不能让它们工作。

我的域名是:

SELECT A.id,GROUP_CONCAT(B.timestamp) AS event1, GROUP_CONCAT(C.timestamp) AS event2 FROM (select distinct id from test) A
   LEFT JOIN test B ON B.id=A.id and B.event='event1'
   LEFT JOIN test C ON C.id=A.id and C.event='event2' GROUP BY A.id

我的控制器类是:

class Role {

String roleName

Role(String _roleName) {
    roleName = _roleName
}

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

}

在测试/单元下我有类RoleControllerSpec:

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

...
}

当我使用test-app -unit RoleController运行测试时,它给出了以下例外情况:

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"

}
}

在我的测试中,似乎控制器为空。 在第一个测试中,controller.index()为null。在第二个测试中,def模型= controller.create()没有创建对象,那么当我尝试访问model.roleInstance时,它无法获取属性。

任何想法都会受到赞赏。 谢谢!

1 个答案:

答案 0 :(得分:2)

由于您使用的是响应而不是简单地从控制器返回地图,因此您需要检查模型属性

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

    when:
    controller.index()

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

我建议您阅读有关测试控制器https://grails.github.io/grails-doc/2.5.x/guide/testing.html#unitTestingControllers

的文档