How to mock service in groovy/src class under test with Grails 3.3.x

711 Views Asked by At

I've recently upgraded to grails 3.3.1 and realised that grails.test.mixin.Mock has been pulled to separate project which has been build just for backward compatibility according to my understanding org.grails:grails-test-mixins:3.3.0.

I've been using @Mock annotation to mock Grails service injected into groovy/src class under test. What is the tactic to mock collaborating services in this case? Is there anything from Spock what I can use or should I fallback to grails-test-mixins plugin?

Class under test: import gra

ils.util.Holders

import grails.util.Holders

class SomeUtilClass {

    static MyService myService = Holders.grailsApplication.mainContext.getBean("myService")

    static String myMethod() {
        // here is some code
        return myService.myServiceMethod()
    }
}

My test spec (Grails 3.2.1):

import grails.test.mixin.Mock
import spock.lang.Specification

@Mock([MyService])
class ValidatorUtilsTest extends Specification {

    def 'my test'() {
        when:
            def result = SomeUtilClass.myMethod()
        then:
            result == "result"
    }
}
3

There are 3 best solutions below

2
On BEST ANSWER

Due to you use Holders.grailsApplication in your SomeUtilClass, you can try to add @Integration annotation:

import grails.testing.mixin.integration.Integration
import spock.lang.Specification
@Integration
class ValidatorUtilsTest extends Specification {

    def 'my test'() {
        when:
        def result = SomeUtilClass.myMethod()
        then:
        result == "result"
    }
}

Not sure, but hope it work for you.

1
On

Try with this code

@TestMixin(GrailsUnitTestMixin)
@Mock([your domains here])
class ValidatorUtilsTest extends Specification {

    static doWithSpring = {
       myService(MyService)
    }

    def 'my test'() {
        when:
            def result = SomeUtilClass.myMethod()
        then:
            result == "result"
    }
}
0
On

Remove the @Mock annotation and implement ServiceUnitTest<MyService> in your test class.