unit-testinggrailsgrails-2.2

Using multiple mockFor() in grails 2.2.3 unit test


I want to write a unit test for my controller which uses multiple services inside it. How can I use multiple mockFor() for services? Tnx.


Solution

  • For example using spock for testing:

    class ExampleControllerUnitSpec extends Specification {
        def anyService
        def anotherService
    
    
        def setup() {
            anyService = Mock(AnyService)
            controller.anyService = anyService
    
            anotherService = Mock(AnotherService)
            controller.anotherService = anotherService
        }
    
        def "test"(){
            when:
                controller.action()
            then:
                1 * anyService.doSomething() >> "result"
                3 * anotherService.doSomethingElse() >> "result2"
        }
    }