register
other register

Monday, June 07, 2010

Grails Controller Unit Test

import grails.converters.JSON

class PersonController {
    def personService

    def jsonPeople = {
        def people = personService.getPerson('usrname', 'passwd')
        render people as JSON
    }
}



class PersonService {

    static transactional = true

    def getPerson(String usrname, String password) {
        // some business logic
     return [firstname: 'joe', lastname: 'blog']
    }
}



import grails.test.*
import grails.converters.JSON

class PersonControllerTests extends ControllerUnitTestCase {
protected void setUp() {
super.setUp()
}

protected void tearDown() {
super.tearDown()
}

void testJsonResponse() {
controller.params.username= 'usrname'
controller.params.password = 'passwd'
              
                // mock the colloaborator
def personControl = mockFor(PersonService)
personControl.demand.getPerson(1..1) { String x, String y ->
                        // the number of parameters and return type have to match the method
return [firstname: 'joe', lastname: 'blog']
}
controller.personService = personControl.createMock()
controller.jsonPeople()

//parse the JSON
def controllerResponse = controller.response.contentAsString
def jsonResult = JSON.parse(controllerResponse)

//navigate the JSON as an object
assertEquals 'joe', jsonResult.username
assertEquals 'blog', jsonResult.password

}
}

No comments: