如何在Grails集成测试中部分模拟服务

时间:2015-08-19 19:45:37

标签: grails groovy spock

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

我的规格如下:

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

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

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调用,而不是后续调用实际方法。为什么会这样?

完整的项目可用here

1 个答案:

答案 0 :(得分:0)

试试这个:

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而不是Stub。

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