Saturday, September 4, 2010

Testing Grails UrlMappings

One thing that often gets overlooked in testing Grails applications is testing any changes you may have made to UrlMappings.groovy. It's understandable that this would happen, but here is how to fix that.

Let's say you have the following in your UrlMappings.groovy

class UrlMappings {
static mappings = {
"/login"(controller: "security", action:"login")
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
}

Really nothing much going on here with the one exception of the custom mapping of /login to the security controller login action. So that's really what we want to test, and here is how:

class UrlMappingsTestCase extends GrailsUrlMappingsTestCase {
void testMappings() {
assertUrlMapping("/login",
controller: "security",
action: "login"
)

assertForwardUrlMapping(500, view: "error")
}
}

That's the basics. Nothing too complicated going on here. I even threw in an example of testing status code (500 in this case) and forwarding. GrailsUrlMappingsTestCase has other asserts that can be used to test other types of mappings so you might want to to read the source.

Remember, as a rule of thumb: "If it's important enough to write, it's important enough to test."

No comments:

Post a Comment