如何在grails单元测试中使用VndErrorJsonRenderer

时间:2014-03-07 15:48:13

标签: unit-testing grails

我正在编写控制器单元测试,我想在创建失败时测试json结果。

如何在单元测试中注册VndErrorJsonRenderer?我在setup()中尝试了简单的defineBeans但它不起作用:(

import com.vividsolutions.jts.geom.Coordinate
import grails.transaction.Transactional
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap

import static org.springframework.http.HttpStatus.CREATED
import static org.springframework.http.HttpStatus.NO_CONTENT

@Transactional(readOnly = true)
class UserController {

    static namespace = "v1"

    static allowedMethods = [profile: 'GET', create: "POST", update: "PUT", delete: "DELETE"]
    static responseFormats = ['json', 'vnd.error+json']

    def springSecurityService

    def geometryFactory


    /**
     * Saves a resource
     */
    @Transactional
    def create() {
        User instance = createResource(params)

        instance.validate()
        if (instance.hasErrors()) {
            respond instance.errors, view: 'create' // STATUS CODE 422
            return
        }

        instance.save flush: true

        respond instance, [status: CREATED]
    }

    protected User createResource(GrailsParameterMap params) {
        Double x = params.double("location.x", 0)
        Double y = params.double("location.y", 0)
        User user = new User()
        bindData(user, params, [include: ['username', 'password', 'profile.*']])
        if (x > 0 && y > 0)
            user.location = geometryFactory.createPoint(new Coordinate(x, y))
        else
            user.location = null
        user.roles = []
        user.roles.add(Role.findByAuthority(Role.ROLE_USER))
        return user
    }



}

我的测试:

@Before
void setup() {
    defineBeans {
        vndJsonErrorRenderer(VndErrorJsonRenderer)
    }
}
void "Test the create action with a non unique username"() {
        User.metaClass.encodePassword = {
            "aaa"
        }
        // Create first user
        assertNotNull getValidUser().save(flush: true)

        when: "The create action is executed with a username already used"
        def user = getValidUser()
        controller.request.addHeader("Accept", "application/vnd.error+json,application/json")
        controller.request.contentType = "application/json"
        controller.request.content = JsonMapperUtil.mapAsJson(user)?.getBytes()
        controller.create()

        then: "The response status is UNPROCESSABLE_ENTITY and the username unique error is returned"
        println response.text
        response.status == UNPROCESSABLE_ENTITY.value
        def json = JSON.parse(response.text)
        assertNull "VND format not returned", json.errors
    }

我正在使用grails 2.3.6和restful controller。

由于

1 个答案:

答案 0 :(得分:0)

如果您要显示依赖于响应的位置,最好将其更多地作为集成测试进行测试,以便所有可能与响应交互的组件都为您着线。

在测试中所需的bean的单元测试中,我发现最容易将它们直接设置在被测试的类中。