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.
- Mock the PersonService using the mockFor method
- Set expectations on the PersonService
- Dependency inject the mocked personService into the controller instance.
- Invoke the controller code
- Verify all the expectations are met
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!