Monday, April 26, 2010

How to use the mocks to verify behaviour in grails

As you can probably see, I am completely vella (word in Hindi which means jobless) today!  Have set a personal record of posting so many blogs in a single day!

Based on the feedback i have received, here's another post in the how-to series.  This one shows you how to create mocks, on which expectations could be set and finally verify that all expectations were satisfied.

For the sake of this post as well I will use our very old PersonController.

Lets take the example of my good old friend, YES the PersonController

Yes, you are right I am actually in love with PersonController :)

What are we testing - What are we upto today!:

PersonController will invoke save method on the PersonService to actually save the person.  We want to verify this behavior.

Controller Code:

Here's how the controller code looks like

We are specifically interested in mocking the personService.save() method.  Have already explained how to test rest of the code in my previous posts here and here.

How will we test it - How do they do it!:

GrailsUnitTestCase class provides a superb method call mockFor (to create mock objects!)  How simple is that!  Using mockFor method we could create mocks for any class.  We could set expectations on the mock and finally verify that all expectations are met.

The test case steps to tests the above code.
  1. Mock the PersonService using the mockFor method
  2. Set expectations on the PersonService
  3. Dependency inject the mocked personService into the controller instance.
  4. Invoke the controller code
  5. Verify all the expectations are met
Thats all.  Pretty easy ha!   
   
Test code looks like this:

Yes, that's all!  As we can see, grails adds extremely flexible and powerful mocking support.  Use it!

As usual feedback, comments and complaints are welcome!
Have some Fun!