单元测试控制器方法? [英] Unit testing a controller method?

查看:145
本文介绍了单元测试控制器方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的控制器方法:

I have a controller method like such:

def search = {
    def query = params.query

            ...

    render results as JSON
}


b $ b

如何单元测试这个?具体来说,我如何调用search来设置 params.query ,如何测试方法的结果 render ?是否有一种方法来模拟render方法,可能?

How do I unit test this? Specifically, how do I call search to set params.query, and how do I test the results of the method render? Is there a way to mock the render method, perhaps?

推荐答案

子类 grails.test.ControllerUnitTestCase 进行单元测试。 Grails将自动实例化您的控制器,并模拟渲染和重定向的版本,使您可以轻松地测试结果。只需将测试输入分配给controller.params即可设置测试。

Subclass grails.test.ControllerUnitTestCase for your unit tests. Grails will automatically instantiate your controller and mock out versions of render and redirect that allow you to test the results easily. Just assign the test inputs to controller.params to set up the test.

示例:

class SomethingController {
    def search = {
        def query = params.query
        ...stuff...
        render results as JSON
    }
}

测试如下:

class SomethingControllerTests extends grails.test.ControllerUnitTestCase {
    void testSearch() {
        controller.params.query = "test query"
        controller.search()
        assertEquals "expected result", controller.response.contentAsString
    }
}

注意:如果您需要一个完整的集成环境和数据库,您也可以使用ControllerUnitTestCase进行集成测试。

Note: you can use ControllerUnitTestCase for integration tests too, if you need a full integration environment complete with database.

这篇关于单元测试控制器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆