Grail Junit控制器测试:request.withformat

时间:2014-07-22 15:33:01

标签: grails junit

我的任务是为控制器代码的这一部分编写(Grails)Junit集成 - 我之前从未见过类似的东西。这是一个用于创建和填充常见问题列表的项目; faq由类别,问题和答案字段组成。问题I的方法部分要测试如下:

static allowedMethods = [index: 'GET', show: 'GET', create: 'GET', edit: 'GET', save: 'POST', update: 'PUT', faq:'GET', delete:'DELETE']

... more stuff

    @Transactional
    def save(Faq faqInstance) {
... other stuff....

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'faq.label', default: 'FAQ'), faqInstance.id])
                redirect faqInstance
            }
            '*' { respond faqInstance, [status: CREATED] }
        }
    }

我还在学习这些东西,所以这实际上可能比我的知识更容易。 :)我已经开始嘲笑Junit测试输入一个非常通用的常见问题,但我不确定它应该返回什么或者如何继续....

void "test save with request of form"(){
    def cont = new FaqController()
    cont.request.method = 'POST'
    cont.params.category = 'General'
    cont.params.question = "This is a question"
    cont.params.answer = "This is an answer"
    cont.save()
    //what to return?   
}

感谢您的帮助,如果我忽略了一些显而易见的事情,请原谅我的无知。 :)

-Ryan

1 个答案:

答案 0 :(得分:0)

您必须检查controller.response,如下所示:

void testControllerRespondsWithJson () {
    def controller = new FooController()
    controller.request.method = 'POST'
    controller.params.category = 'General'
    controller.params.question = "This is a question"
    controller.params.answer = "This is an answer"
    controller.response.format = 'json'

    controller.save ()

    def json = controller.response.json
    assert controller.response.status == HttpServletResponse.SC_CREATED
    assert json.category == controller.params.category
    // ...
}

controller.response.text是“标准”结果,String。如果是json结果,则更容易将其解析为json对象并检查它。