Thursday, December 30, 2010

mockFor and MockFor in Grails

I recently came across a small shortcoming in Grails' mockFor feature. I wasn't able to return a value from a service that was mocked. I get an error where the return value is always a closure, not the value I intended. (Note this occurred in grails v1.1).

I found that using Groovy's MockFor is just as convenient and does not contain this shortcoming.

Concept Overview

Often a developer would like to use mocks to isolate code and verify that a unit of code is operating correctly. The rationale is: "Given that collaborators are behaving in a specific way, the code under test behaves as expected." In other words, if collaborator returns A, then the code under test will perform B. If the collaborator returns C, then the code under test will perform D.

Many Java mock frameworks provide this ability, including EasyMock and JMock, to name a few.

mockFor Shortcoming

On a grails project, I wanted a mock to return a certain value. This did not work. Let me provide an example to illustrate the problem.