Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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.

like image 801
HypeMK Avatar asked Nov 24 '15 22:11

HypeMK


1 Answers

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;
    }
}
like image 189
jeremija Avatar answered Nov 16 '22 03:11

jeremija