I have a controller like this:
class NotificationApiController {
def countService
def getCount() {
def results = countService.getCount()
render results as JSON
}
}
And the controller test like this:
Closure doWithSpring() {{ ->
countService(CountService)
}}
CountService countService
def setup() {
}
def cleanup() {
}
void "test getCount method"() {
given:
def countService = Mock(CountService) {
1 * getCount(_) >> [count: 2]
}
when:
def y = controller.getCount()
then:
y == [count: 2]
}
It appears it always calls into the actual CountService injected in Closure doWithSpring(), not my mock countService, but without the definition of Closure doWithSpring()..., I will get this error
Cannot invoke method getCount() on null object
java.lang.NullPointerException: Cannot invoke method getCount() on null object
The documentation on unit testing in 4.0 is really limited and I am not exactly sure how should I do this. I see some samples in Grails 2.3 or 3.3. version, but they all seems not working for me, mostly due to the difference of Spock and Mixin framework I guess. Any suggestions on how to do this?