Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

controller.modelAndView is null in integration test

Given this action in a controller:

def listBlockedMembers() {
    def blocked = UserBlock.findAllByUser(springSecurityService.currentUser)

    render(view:'listBlockedMembers', model:[blocked:blocked])
}

in my integration test the model and view works fine:

def blocked = controller.modelAndView.model['blocked']
assertEquals 2, blocked.size()

but if I pass the model from the action like this:

def listBlockedMembers() {
    def blocked = UserBlock.findAllByUser(springSecurityService.currentUser)
    [blocked:blocked]
}

I get a null pointer exception accessing controller.modelAndView (null pointer on the modelAndView attribute itself)

My integration test extends GroovyTestCase. While the first action works, the second is less code, and I wonder why the null pointer exception would occur. In development the gsp renders the same for both actions.

like image 538
spock99 Avatar asked Sep 13 '26 23:09

spock99


1 Answers

There's actually a Grails bug for this, and it has to do with the two return types being handled differently:

There are 2 scenarios being discussed here. One is a scenario where a method in a controller returns a Map and one is a scenario where the method in a controller does not return a Map. For the case where the method does not return a Map, for the sake of this discussion we are talking about the method having invoked the render method.

So it looks like when returning a map, it may be better to treat it as a regular method (and dealing with the returned value) than calling controller.modelAndView. For example:

Map response = controller.listBlockedMembers()
assert response.blocked
like image 75
Igor Avatar answered Sep 16 '26 05:09

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!