开发者

Grails get view of controller

I'm trying to make an Integration Test case for a controller and I need to get the view name of the co开发者_Python百科ntroller that's being tested.

I'm trying to do it this way:

controller?.modelAndView?.getViewName()

But the modelAndView object is null. The controller object is not null and passes other tests.

Any idea on why I'm getting modelAndView null? from what I've searched that's the way to get the view name of the controller.

Thanks for your help.


I had a similar issue before where I needed to get the model in an integration test after a controller action method was executed, so what I did was that I changed the render method from the Controller to be able to get the map that is passed to it in order to be able to get the model. So I had a variable in the test method called renderMap, then in I did

Map renderMap

registerMetaClass(MyController.class)
MyController.metaClass.render = {Map m ->
  renderMap = m
}
...
// Instantiate controller
// Call controller action

Then I was able to access some of the objects I set in the model like this:

def someObject = renderMap.model.someObject

So with this you should be able to do:

String view = renderMap.view

At some point you might want to restore your controller's metaClass as it was.


The test case worked on older versions of Grails but since 1.3.5 it wasn't working, I had to add the line to add the record.id to the params like this:

    void testUpdateSaveError(){

    recordWrongParams.each{key, value->
        controller.params.put(key,value)
    }
    controller.params.put("id", record.id)      
    controller.update()         

    assertEquals controllerPath + "/edit", controller?.modelAndView?.getViewName()      
}

After that it's working

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜