我是 grails 新手。 我只是搭建一个域类员工,如下所示
class Employee {
String firstName
String lastName
static constraints = {
}
}
我正在尝试使用 spock 在 EmployeeController 中编写一个关于列表操作的单元测试。 Controller 如下所示
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
谁能建议一下,如何解决这个问题
提前谢谢
最佳答案
单元测试环境在模拟之前不会提供可用的域。
使用@Mock(Employee)
并在Employee中设置测试数据来测试list()操作。
关于unit-testing - grails 单元测试 spock 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23466262/