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

I am updating the application from Grails 2.4.4 to Grails 3.0.9, and I cannot find any information on how to do mockFor, createMock and requirements 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" just left, even from the documentation. What is the Grails 3 way?

UPDATE:

I donโ€™t want to rewrite thousands of tests written by Grails 'mockFor' style in Spock's interaction style, so I came up with this solution:

  • replace mockFor () with the new MockFor ()
  • replace createMock () with proxyInstance ()
  • move calls to fooBean.fooService = fooService.proxyInstance () after requirements

Without further changes, this โ€œjust worksโ€ in Grails 3.

+4
2

Spock :

@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;
    }
}
+8

grails 2, mockFor, , HypeMK :

  • groovy MockFor: import groovy.mock.interceptor.MockFor
  • mockFor new MockFor
  • createMock() proxyInstance()
  • verify()
+4

Source: https://habr.com/ru/post/1617337/


All Articles