Mocking in Grails unit tests

Integration and functional tests in Grails are quite slow depending on the complexity of your code base. This results in slow continuous integration cyles. Pure unit tests are there for a better alternative most of the time. But mocking all the dependencies especially the Grails meta programming magic or automatically Spring injected beans can be really hard.

Fortunately Grails comes with a few very helpful base classes for unit testing:

  • GrailsUnitTestCase
  • MvcUnitTestCase
  • ControllerUnitTestCase
  • TagLibUnitTestCase

With their help you are able to mock domain classes, services, controllers tag libs and the injected logger for instance.

protected void setUp() {
  // mock books, provide two book test instances
  mockDomain(Book, [new Book(id:1), new Book(id:2)])
  // inject an mock logger to BookService instances
  mockLogging BookService

Don’t forget to call super.setUp() and super.tearDown() as you overwrite one of these methods in your implementation. Otherwise these test base classes do not behave correctly and result in diverse errors.

Deeper informations on how to use these base classes and how to mock Grails artifacts and the dependencies can be found in the official Grails documentation or in this slightly outdated developerworks article.

Short URL for this post:
This entry was posted in Groovy and Grails and tagged , , . Bookmark the permalink.

2 Responses to Mocking in Grails unit tests

  1. Glenn Saqui says:

    If you are mocking in Grails you should have a look at GMock. In my opinion it’s the best way to mock out services.

  2. Lettie Epel says:

    Danke für den netten Bericht!

Leave a Reply

Your email address will not be published. Required fields are marked *