简体   繁体   中英

How to test interaction of a grails service method using spock framework

I am using grails 2.5.4 and the spock framework. I have the following service in my grails proyect

class MyService {

   void method1(Param param) {
       if (param == null) {
          return
       }
       method2(param)
       method3(param)
   }

   void method2(Param param) { 
       println param
   }

   void method3(Param param) { 
       println param
   }
}

All methods have void return type. I want to check out that in the case of not null param all methods are called.

My test is something like this

@TestFor(PaymentService)
class MyServiceSpec extends Specification {
   void testMethods() {
       when:
       service.method1(new Param())

       then:
       1 * service.method2(*_)
       1 * service.method3(*_)
   }
}

But It always shows 0 interactions for method2 and method3. I know they are called (I used the debugger). I know I can Mock services of the main service, but I don't know how to test interactions on the main service or mock specific methods of the service to test if they were called.

I am not sure if I explained it well.....

You could test it with a Spy using something like this:

class MyServiceSpec extends Specification {
    void 'test methods'() {
        given:
        def myService = Spy(MyService)

        when:
        myService.method1(new Param())

        then:
        1 * myService.method2(_ as Param)
        1 * myService.method3(_ as Param)
    }

}

(note that you do not need @TestFor for a test like that)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM