Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何使用spock框架测试grails服务方法的交互_Unit Testing_Grails_Spock - Fatal编程技术网

Unit testing 如何使用spock框架测试grails服务方法的交互

Unit testing 如何使用spock框架测试grails服务方法的交互,unit-testing,grails,spock,Unit Testing,Grails,Spock,我正在使用Grails2.5.4和spock框架。我的grails项目中有以下服务 class MyService { void method1(Param param) { if (param == null) { return } method2(param) method3(param) } void method2(Param param) { println param

我正在使用Grails2.5.4和spock框架。我的grails项目中有以下服务

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
   }
}
所有方法都具有void返回类型。我想检查一下,在NOTNULL param的情况下,是否调用了所有方法

我的测试是这样的

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

       then:
       1 * service.method2(*_)
       1 * service.method3(*_)
   }
}
但它始终显示method2和method3的0个交互。我知道它们被调用(我使用了调试器)。我知道我可以模拟主服务的服务,但我不知道如何测试主服务上的交互或模拟服务的特定方法来测试它们是否被调用


我不确定我是否解释得很好….

你可以用一个间谍来测试它,如下所示:

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

}

(请注意,对于这样的测试,您不需要
@TestFor

我不确定该注释的作用。明天我将测试你的解决方案并接受你的答案:)它非常有效!!。。谢谢我将提出一个关于代码设计的新问题:D