3

I have a simple grails service:

@Transactional
class SearchService {
    def doSomething() {
        10
    }
}

with a simple unit test:

class SearchServiceSpec extends Specification implements ServiceUnitTest<SearchService>{

    def setup() {
    }

    def cleanup() {
    }

    void "test something"() {
        expect:
        service.doSomething() == 10
    }
}

When I run the test, I get the following exception:

enter image description here

Anyone know what this means?

Strange thing is it works if I change doSomething to getSomething and then do service.something.

I have following versions: | Grails Version: 3.3.0 | Groovy Version: 2.4.11 | JVM Version: 1.8.0_60

Emmanuel John
  • 2,296
  • 1
  • 23
  • 30
  • Using a 'get' method is exactly what they have in the documentation : https://testing.grails.org/latest/guide/index.html#unitTestingServices Add a @Mock() annotation to your class and it should wire GORM and work. (Grails prior to 3.3). I don't know how they changed it in 3.3. – bassmartin Sep 08 '17 at 13:22

1 Answers1

8

This is due to the fact that the getter method is not having transactional behavior applied to it. To test a transactional method, you need to have a GORM implementation setup. The easiest way to do that for your test is to implement grails.testing.gorm.DataTest.

James Kleeh
  • 12,094
  • 5
  • 34
  • 61
  • 2
    It would be nice to have this documented in the official documentation in the 'unit testing services' section. Since Services are generated with transactional behavior by default, it's an important fact to have in the documentation. – bassmartin Sep 08 '17 at 13:36
  • Then I would encourage you to submit a PR to the documentation. – James Kleeh Sep 08 '17 at 14:59
  • That fixed it. I agree with @bassmartin I couldn't have figured this out without a SO post. – Emmanuel John Sep 09 '17 at 13:39