unit-testinggrailsgrails-2.0grails-services

Grails: Mocking a service and its method inside another service


I have a following service:

class MyMainService {

    def anotherService;

    def method1("data") {
         def response = anotherService.send("data")
    }

}

anotherService is a bean defined in grails resources.groovy

I want to unit test the method1 in MyMainService by mocking anotherService.send("data")

How do I mock anotherService bean and the return value of it's send() method and inject into my MyMainServiceSpec test class?

I am using grails 2.3.8.

Thanks.


Solution

  • You can use the default mocking framework built into grails or elect to use the Spock framework mocking style. I prefer the Spock framework, but the choice is yours. Here is an example of how to do it with the grails mockFor method that is available in your unit specs.

    To test MyMainService with the default grails mocks.

    @TestFor(MyMainService)
    class MyMainServiceSpec extends Specification {
    
        @Unroll("method1(String) where String = #pData")
        def "method1(String)"() {
            given: "a mocked anotherService"
            def expectedResponse = [:]  // put in whatever you expect the response object to be
    
            def mockAnotherService = mockFor(AnotherService)
            mockAnotherService.demand.send { String data ->
                 assert data == pData
                 return expectedResponse // not clear what a response object is - but you can return one. 
            }
            service.anotherService = mockAnotherService.createMock()  // assign your mocked Service 
    
            when:
            def response = service.method1(pData)
    
            then:
            response
            response == expectedResponse   
    
            where:
            pData << ["string one", "string two"]
        }
    }