如何在Grails集成测试中部分模拟服务 [英] How to partially mock service in Grails integration test

查看:230
本文介绍了如何在Grails集成测试中部分模拟服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为调用服务方法的控制器编写测试.我想在该服务中模拟一个依赖方法.

I am attempting to write a test for a controller which calls a service method. I would like to mock a dependent method within that service.

我的规格如下:

MyController myController = new MyController()
def mockMyService

def "My spy should be called"() {
    when:
        mockMyService = Spy(MyService) {
            methodToSpy() >> {
                println "methodToSpy called"
            } // stub out content of this fn
        }
        myController.myService = mockMyService
        myController.callService()

    then:
        1 * mockMyService.methodToSpy()
}

当我尝试运行此测试时,出现以下错误:

When I attempt to run this test, I get the following error:


Failure:  |
My spy should be called(spybug.MyControllerSpec)
 |
Too few invocations for:
1 * mockMyService.methodToSpy()   (0 invocations)
Unmatched invocations (ordered by similarity):
1 * mockMyService.serviceMethod()
1 * mockMyService.invokeMethod('methodToSpy', [])
1 * mockMyService.invokeMethod('println', ['in serviceMethod about to call methodToSpy'])
1 * mockMyService.invokeMethod('println', ['Back from methodToSpy'])

如您所见,Spock正在捕获Groovy invokeMethod调用,而不是对实际方法的后续调用.为什么会这样?

As you can see, Spock is capturing the Groovy invokeMethod call, not the subsequent call to the actual method. Why is this happening?

完整的项目可在此处获得.

推荐答案

尝试一下:

def "My spy should be called"() {
    given:
    mockMyService = Mock(MyService)
    myController.myService = mockMyService

    when:
    myController.callService()

    then:
    1 * mockMyService.methodToSpy(_) >> { println "methodToSpy called" }   
}

根据存根的spock文档,如果要使用基数,则必须使用Mock而不是存根.

According to the spock documentation for stubs, if you want to use the cardinality, you must use a Mock and not a Stub.

http://spockframework.github.io/spock/docs/1.0/interaction_based_testing.html#_stubbing

这篇关于如何在Grails集成测试中部分模拟服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆