如何使用 spock 框架测试 grails 服务方法的交互
How to test interaction of a grails service method using spock framework
我正在使用 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 return 类型。我想检查在参数不是 null 的情况下是否调用了所有方法。
我的测试是这样的
@TestFor(PaymentService)
class MyServiceSpec extends Specification {
void testMethods() {
when:
service.method1(new Param())
then:
1 * service.method2(*_)
1 * service.method3(*_)
}
}
但它始终显示方法 2 和方法 3 的交互为 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
进行这样的测试)
我正在使用 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 return 类型。我想检查在参数不是 null 的情况下是否调用了所有方法。
我的测试是这样的
@TestFor(PaymentService)
class MyServiceSpec extends Specification {
void testMethods() {
when:
service.method1(new Param())
then:
1 * service.method2(*_)
1 * service.method3(*_)
}
}
但它始终显示方法 2 和方法 3 的交互为 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
进行这样的测试)