![](/img/trans.png)
[英]Grails 2.5.1 Restful controller spock unit test fails with 406 when running in Intellij IDEA
[英]Controller always null in Spock unit test using Grails 2.5.1
我是使用Grails 2.5.1的新手。 我需要運行一些單元和集成測試,但無法使其正常運行。
我的域類是:
class Role {
String roleName
Role(String _roleName) {
roleName = _roleName
}
static constraints = {
roleName(blank: false, nullable: false)
}
String toString(){
"$roleName"
}
}
我的控制器類是:
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.index()為null。 在第二個測試中,def model = controller.create()未創建對象,然后當我嘗試訪問model.roleInstance時無法獲取該屬性。
任何想法將不勝感激。 謝謝!
由於您使用的是響應而不是簡單地從控制器返回映射,因此您需要檢查model屬性
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.