Wednesday, April 28, 2010

Mock Testing with Grails

For unit testing controllers that make calls to injected spring beans, we can use Grails' mock framework.

Take for example a Controller and Service class defined as follows
class MyService {
boolean transactional = true

def serviceMethod(param1) {
return 'hi'
}
}

class MyDomainController {
def myService

def doSomething = {
def val = myService.serviceMethod('input1')
return val }
}

Our test case for the doSomething closure would look as follows
import grails.test.*

class MyDomainControllerTests extends ControllerUnitTestCase {

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

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

void testSomething() {
GrailsMock serviceMock = mockFor(MyService)

/*
* Mock the method being called
* the 1..1 specifies the min & max number of times the method is expected to be called
* the closure defines the code executed each time the method is called
*/

serviceMock.demand.serviceMethod(1..1) {param1 ->
assertEquals 'input1', param1
return 'hi'
}

/*
* The service needs to be manually set in the controller
*/

controller.myService = serviceMock.createMock()

assertEquals 'hi', controller.doSomething()

/*
* Verifies that the service was accessed
* in the manner established earlier.
*/

serviceMock.verify()
}
}

No comments:

Post a Comment