Grails Testing Plugin Log Mocking

I’m a big fan of the famous Grails Testing Plugin, which is used to mock domain classes, controllers and many more things usually needed in my unit tests for Grails.  Here’s a quick example from its documentation:

class BookTests extends GrailsUnitTestCase {
 void testConstraints() {
 def existingBook = new Book(title: "Misery", author: "Stephen King")
 mockForConstraintsTests(Book, [ existingBook ])

 // Validation should fail if both properties are null.
 def book = new Book()
 assertFalse book.validate()
 assertEquals "nullable", book.errors["title"]
 assertEquals "nullable", book.errors["author"]

 // So let's demonstrate the unique and minSize constraints.
 book = new Book(title: "Misery", author: "JK")
 assertFalse book.validate()
 assertEquals "unique", book.errors["title"]
 assertEquals "minSize", book.errors["author"]

 // Validation should pass!
 book = new Book(title: "The Shining", author: "Stephen King")
 assertTrue book.validate()

Recently in a Grails 1.0.5 project I had to unit test a service method. Because of several “log” statements, I had the dreaded

No such property: log for class:  SubscriptionService

Fortunately, the testing framework has the excellent mock Logging() method in place for that, which provides a mock implementation of the “log” property for the given class, in my case SubscriptionService. Here’s how I created my setUp() method:

void setUp() {
 mockLogging(SubscriptionService.class, true)

This resulted in

Cannot invoke method containsKey() on null object

It was a NPE on the following part inside GrailsUnitTestCase.groovy:

protected void registerMetaClass(Class clazz) {
 // If the class has already been registered, then there's
 // nothing to do.
 if (savedMetaClasses.containsKey(clazz)) return

After some digging around, it almost seemed to trivial to fix thix. Just add called the super’s setUp() first.

void setUp() {
 mockLogging(SubscriptionService.class, true)

Happy mocking!