grails单元测试spock问题

时间:2014-05-05 06:35:16

标签: unit-testing grails spock

我是grails的新手。  我只是支持一个域级员工,如下所示

class Employee {

    String firstName
    String lastName

    static constraints = {
    }
}

我正在尝试使用spock在EmployeeController中对列表操作编写单元测试。控制器如下所示

class EmployeeController {

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

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10,100)
        [employeeInstanceList: Employee.list(params), employeeInstanceTotal: Employee.count()]
    }
}

然后我写了一个下面给出的测试用例

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(EmployeeController)
class EmployeeControllerUnitSpec extends Specification {

    def 'test index'() {
        when:
        controller.index()

        then:
        // httpcode ? 200
        //println response (GrailsMockHttpServletResponse)
        response.redirectedUrl == '/employee/list'
    }

    def 'test list empty'() {
        when:
        controller.list( 10 )
        // Employee.list()

        then:
        model.employeeInstanceTotal == 0;

    }
}

此处索引的测试用例正常工作,但测试列表空在控制台中呈现一些错误。 控制台中的错误描述是

| Running 2 spock tests... 2 of 2
| Failure:  test list empty(com.test.EmployeeControllerUnitSpec)
|  groovy.lang.MissingMethodException: No signature of method: com.test.Employee.list() is applicable for argument types: () values: []
Possible solutions: list(), list(java.util.Map), last(), last(java.lang.String), last(java.util.Map), first()
    at com.test.EmployeeController.list(EmployeeController.groovy:15)
    at com.test.EmployeeControllerUnitSpec.test list empty(EmployeeControllerUnitSpec.groovy:21)
| Completed 2 spock tests, 1 failed in 3231ms
| Tests FAILED  - view reports in /mnt/hdd2/home/T-2060/workspace/testing/target/test-reports

任何人都可以建议,如何解决这个问题

提前谢谢

1 个答案:

答案 0 :(得分:2)

单元测试环境在被模拟之前不会有域可用。

使用@Mock(Employee)并在Employee中设置测试数据来测试list()操作。