用Grails测试RestfulController

mar*_*rco 4 grails integration-testing json

我正在尝试为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]
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

集成测试如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

我不明白的是controller.response.json只包含"AnotherPerson"而不是两个条目.当我使用run-app启动服务器并使用Rest-Client测试它时我得到两个条目.有任何想法吗?

Jef*_*own 5

您没有提供足够的信息来确定问题是什么,但以下测试通过了2.4.0.

域类:

// grails-app/domain/com/demo/Person.groovy
package com.demo

class Person {
    String name
    Integer age
}
Run Code Online (Sandbox Code Playgroud)

控制器:

// 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

考试:

// 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"}]'
    }
}
Run Code Online (Sandbox Code Playgroud)