【问题标题】:How to test interaction of a grails service method using spock framework如何使用 spock 框架测试 grails 服务方法的交互
【发布时间】:2017-01-31 20:20:41
【问题描述】:

我正在使用 grails 2.5.4 和 spock 框架。我的 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
   }
}

所有方法都有 void 返回类型。我想检查一下,在非空参数的情况下,所有方法都被调用。

我的测试是这样的

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

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

但它总是显示方法 2 和方法 3 的 0 次交互。我知道它们被称为(我使用了调试器)。我知道我可以模拟主服务的服务,但我不知道如何测试主服务上的交互或模拟服务的特定方法以测试它们是否被调用。

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

【问题讨论】:

    标签: unit-testing grails spock


    【解决方案1】:

    您可以使用类似这样的方式使用 Spy 对其进行测试:

    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
    猜你喜欢
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 2012-03-29
    • 2023-03-31
    • 2021-10-24
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    相关资源
    最近更新 更多