我试图为Grails 2.4.0中的RestfulController编写一些集成测试,以JSON格式进行响应。 index() - Method实现如下:
class PersonController extends RestfulController<Person> {
...
def index(final Integer max) {
params.max = Math.min(max ?: 10, 100)
respond listAllResources(params), [includes: includeFields]
}
...
}
集成测试如下所示:
void testListAllPersons() {
def controller = new PersonController()
new Person(name: "Person", age: 22).save(flush:true)
new Person(name: "AnotherPerson", age: 31).save(flush:true)
controller.response.format = 'json'
controller.request.method = 'GET'
controller.index()
assertEquals '{{"name":"Person", "age": "22"},{"name":"AnotherPerson", "age": "31"}}', controller.response.json
}
我不理解的是controller.response.json只包含&#34; AnotherPerson&#34;而不是两个条目。 当我使用run-app启动服务器并使用Rest-Client测试它时我得到两个条目。 任何想法?
答案 0 :(得分:5)
您没有提供足够的信息来确定问题是什么,但以下测试通过了2.4.0。
域类:
// grails-app/domain/com/demo/Person.groovy
package com.demo
class Person {
String name
Integer age
}
控制器:
// grails-app/controllers/com/demo/PersonController.groovy
package com.demo
class PersonController extends grails.rest.RestfulController<Person> {
PersonController() {
super(Person)
}
def index(final Integer max) {
params.max = Math.min(max ?: 10, 100)
respond listAllResources(params)
}
}
测试:
// test/unit/com/demo/PersonControllerSpec.groovy
package com.demo
import grails.test.mixin.TestFor
import spock.lang.Specification
@TestFor(PersonController)
@Mock(Person)
class PersonControllerSpec extends Specification {
void "test index includes all people"() {
given:
new Person(name: "Person", age: 22).save(flush:true)
new Person(name: "AnotherPerson", age: 31).save(flush:true)
when:
request.method = 'GET'
response.format = 'json'
controller.index()
then:
response.status == 200
response.contentAsString == '[{"class":"com.demo.Person","id":1,"age":22,"name":"Person"},{"class":"com.demo.Person","id":2,"age":31,"name":"AnotherPerson"}]'
}
}
答案 1 :(得分:0)
我把这个例子简化了一点。我使用了一个命名对象marshaller,我在bootstrap.groovy中创建(不正确),如下所示:
JSON.createNamedConfig('simplePerson') { converterConfig ->
converterConfig.registerObjectMarshaller(Person) {
JSON.registerObjectMarshaller(Person) {
def map = [:]
map['name'] = it.name
map['age'] = it.age
return map
}
}
}
并在控制器中使用它:
...
JSON.use("simplePerson")
...
通过像这样创建对象编组来解决问题:
JSON.createNamedConfig('simplePerson') { converterConfig ->
converterConfig.registerObjectMarshaller(Person) {
def map = [:]
map['name'] = it.name
map['age'] = it.age
return map
}
}