grailsgrails-3.0grails-3.0.9

Grails 3 Unit Testing: How do you do mockFor, createMock, and demands in Grails 3?


I'm upgrading an application from Grails 2.4.4 to Grails 3.0.9, and I can't find any information on how to do mockFor, createMock, and demands in Grails 3.

I used to do things like this:

fooService = mockFor(FooService)
controller.fooService = fooService.createMock()

fooService.demand.barMethod() { a,b ->
}

But it looks like 'mockFor' is simply gone, even from the documentation. What's the Grails 3 way to do this?

UPDATE:

I don't want to rewrite thousands of tests written with the Grails 'mockFor' style to the Spock style of interactions, so I came up with this solution:

With no further changes, this "just works" in Grails 3.


Solution

  • You can use Spock by default:

    @TestFor(MyController)
    class MyControllerSpec extends Specification {
    
        void "test if mocking works"() {
            given:
            def fooService = Mock(FooService)
            fooService.barMethod(_, _) >> {a, b ->
                return a - b
            }
    
            when:
            def result = fooService.barMethod(5, 4)
    
            then:
            result == 1
        }
    }
    
    class FooService {
        int barMethod(int a, int b) {
            return a + b;
        }
    }