unit-testing - 如何使用Spock框架测试Grails服务方法的交互

标签 unit-testing grails spock

我正在使用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返回类型。我想检查一下,在非null参数的情况下,将调用所有方法。

我的测试是这样的
@TestFor(PaymentService)
class MyServiceSpec extends Specification {
   void testMethods() {
       when:
       service.method1(new Param())

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

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

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

最佳答案

您可以使用以下 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进行这样的测试)

关于unit-testing - 如何使用Spock框架测试Grails服务方法的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41966772/

相关文章:

unit-testing - 高级开发人员和单元测试 - 需要吗?他们可以使用走狗吗?

grails - 我的 Grails 应用服务器不断重新启动

java - 想法 "Groovyc: unable to resolve class"- 在命令行上工作

scala - Spock mock Akka 的 ActorRef

c# - 从 VSTest.Console.exe 向单元测试传递参数或选项

javascript - Jest 模拟特定的配置值

javascript - Zombie.js错误: Timeout: did not get to load all resources on this page

grails - 为Grails 3.0.4配置 Camel 路由

mongodb - 初始化应用程序时出错 : No datastore implementation specified Message: No datastore implementation specified

spring-boot - 在 Spring Boot 应用程序中将 Autowiring 的对象作为模拟注入(inject)到 spock 测试中