1

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"
    }
}
kuceram
  • 3,795
  • 9
  • 34
  • 54

3 Answers3

1

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.

Nic Olas
  • 451
  • 2
  • 10
0

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"
    }
}
elixir
  • 1,394
  • 1
  • 11
  • 21
  • Well, this doesn't work as the dependency injection is done through Holders manually. It throws an exception `java.lang.IllegalArgumentException: GrailsApplication not found`. I can still use @Mock what works. I was asking if there is another better way... – kuceram Nov 29 '17 at 17:38
0

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

James Kleeh
  • 12,094
  • 5
  • 34
  • 61