【问题标题】:Unit testing Grails controller chaining单元测试 Grails 控制器链接
【发布时间】:2014-09-14 14:09:10
【问题描述】:

我无法弄清楚如何测试执行“链接”的控制器操作。我想验证操作。

Grails:2.4.2

控制器:

class MyController {

def index() {

}

def doesChain() {
    chain action: 'index', model: [name: "my name"]
}

}

测试:

@TestFor(MyController)
class MyControllerSpec extends Specification {

def setup() {
}

def cleanup() {
}

void "Action doing chain"() {

    when:
    controller.doesChain()

    then:
    controller.chainModel.name == "my name"
    controller.actionName == "someAction" // fails as actionName == null
}

}

由于 actionName 似乎为空,因此未通过测试操作名称。

【问题讨论】:

    标签: unit-testing grails controller chain


    【解决方案1】:

    你可以做这样的事情......

    @TestFor(MyController)
    class MyControllerSpec extends Specification {
    
        void "Action doing chain"() {
    
            when: 'an action invokes the chain method'
            controller.doesChain()
    
            then: 'the model is as expected'
    
            // either of these should work, you don't need both...
            controller.chainModel.name == "my name"
            flash.chainModel.name == "my name"
    
            and: 'the redirect url is as expected'
            response.redirectUrl == '/my/index'
    
        }
    }
    

    希望对你有帮助。

    【讨论】:

    • 谢谢!实际上已经尝试过了,但只有'/'作为redirectUrl。但是,受您的示例的启发,我创建了新的控制器并对其进行了测试,并且它可以正常工作!它为我的另一个控制器返回“/”的原因是它是 UrlMappings.groovy 中映射的默认值:“/”(控制器:“我的”)。这个配置是在“my/index”刚刚映射到“/”时被提取的。所以问题解决了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    相关资源
    最近更新 更多