7

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:

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

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

HypeMK
  • 331
  • 3
  • 9
  • The answer will depend on which testing framework you are using, which isn't indicated in your question. Are you using Spock? JUnit? Something else? – Jeff Scott Brown Nov 25 '15 at 03:24
  • I've been using the mockFor+createMock+demand pattern from Grails 1.3.7 (GrailsUnitTestCase JUnit style) to Grails 2.4.4 (Specification Spock style). – HypeMK Nov 25 '15 at 17:13

2 Answers2

10

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;
    }
}
jeremija
  • 2,338
  • 1
  • 20
  • 28
6

I was also upgrading a lot of tests from grails 2 that used mockFor and used a similar approach which HypeMK outlined:

  1. add import for groovy's MockFor: import groovy.mock.interceptor.MockFor
  2. rename mockFor to new MockFor
  3. rename createMock() to proxyInstance()
  4. remove calls to verify()
Jay Prall
  • 5,295
  • 5
  • 49
  • 79