kuceram
kuceram

Reputation: 3885

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

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"
    }
}

Upvotes: 1

Views: 748

Answers (3)

Nic Olas
Nic Olas

Reputation: 471

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.

Upvotes: 1

James Kleeh
James Kleeh

Reputation: 12228

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

Upvotes: 0

elixir
elixir

Reputation: 1442

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"
    }
}

Upvotes: 0

Related Questions