I’m trying to mock a service in an integration test for a dynamically scaffolded controller. I get an error indicating that the controller property for the service is not accessible from the test.
It seems that dynamically scaffolded controllers can’t be tested with unit tests at all so I’m using integration tests. I want to mock the service to test error handling in my app. Is this a bug in Grails 2.2.0 or am I just doing it wrong?
The result for grails test-app is:
groovy.lang.MissingPropertyException: No such property: myService for class: MyController
Example:
I have modified the src/templates/scaffolding/Controller.groovy:
class ${className}Controller {
MyService myService
def action() {
render myService.serviceMethod()
}
}
Dynamically scaffolded MyController.groovy:
class MyController {
static scaffold = MyDomainClass
}
Integration test MyControllerTests.groovy:
class MyControllerTests extends GroovyTestCase {
def myController
@Before
void setUp() {
myController = new MyController()
}
void testMock() {
myController.myService = [ serviceMethod : { return "foo" } ] as MyService
controller.action()
}
}
Try using the setter method:
If you execute:
println c.metaClass.methods*.name, you will see that there are methods like getSetMyService() and getGetMyService(). I’m not sure of it, but probably Grails is not adding fields but instead getters for field get/set methods.