简体   繁体   English

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

[英]How to partially mock service in Grails integration test

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. 我想在该服务中模拟一个依赖方法。

My spec is as follows: 我的规格如下:

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'])

As you can see, Spock is capturing the Groovy invokeMethod call, not the subsequent call to the actual method. 如您所见,Spock正在捕获Groovy invokeMethod调用,而不是对实际方法的后续调用。 Why is this happening? 为什么会这样呢?

The complete project is available here . 完整的项目在这里

Try this: 尝试这个:

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

    when:
    myController.callService()

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

According to the spock documentation for stubs, if you want to use the cardinality, you must use a Mock and not a Stub. 根据存根的spock文档,如果要使用基数,则必须使用模拟而不是存根。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM