Unit Testing Controller based RESTful Services in Grails
Just a quick example on how you can test the various HTTP methods for your Grails controllers.
Controller:
1 2 3 4 5 6 7 8 9 10 11 12 | def show = { def user = User.get(params.id) if(user) { withFormat { html user:user xml { render user as XML } json { render user as JSON } } } else { response.sendError 404 } } |
Unit Tests:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | void testXMLResponse() { mockDomain(User, [new User(id:1, username:"fred", password:User.encrypt("letmein"))]) controller.request.method = 'GET' controller.request.contentType = 'text/xml' controller.request.format = 'xml' controller.params.id = '1' controller.show() def user = XML.parse(controller.response.getContentAsString()) assert user.id == 1 assert user.username == "fred" assert user.password == User.encrypt("letmein") } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | void testJSONResponse() { mockDomain(User, [new User(id:1, username:"fred", password:User.encrypt("letmein"))]) controller.request.method = 'GET' controller.request.contentType = 'text/json' controller.request.format = 'json' controller.params.id = '1' controller.show() def user = JSON.parse(controller.response.getContentAsString()) println controller.response.contentAsString assert user.id == 1 assert user.username == "fred" assert user.password == User.encrypt("letmein") } |
Pretty simple!
Posted in: REST, grails, groovy
Leave a comment
You must be logged in to post a comment.

