繁体   English   中英

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

[英]How to use VndErrorJsonRenderer in grails unit test

我正在编写控制器单元测试,当创建失败时,我想测试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。

谢谢

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

在针对被测类中需要什么bean的单元测试中,我发现直接在被测类上设置它们是最简单的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM