Oops I forgot I have some logging inside my CachingService class. At runtime Grails auto-magically injects a "log" property into service classes. If my test was an integration test then there wouldn't be a problem. So I have two options, either mock out the logger or run my test as an integration tests. I decided to mock out the logger, which required me to do the following:
1. Create a MockLogger class (primarily since I will probably have to mock out the logger in other classes in the future)
class MockLogger {
void info(message) {}
void warn(message) {}
void debug(message) {}
void error(message) {}
}
2. Inject my MockLogger as a property named "log" via getLog() into my service class via ExpandoMetaClass
void setUp() { CachingService.metaClass.getLog = { -> new MockLogger() }
}3. Reset the state of CachingService before dynamically adding the property "log"
void tearDown() {
def remove = GroovySystem.metaClassRegistry.&removeMetaClass
remove CachingService
}
There may be other ways to mock out the logger, but this approach seemed simple enough. Do you have an easier approach? If so please drop a comment.