简体   繁体   English

Spock测试中针对Grails服务的交互太少

[英]Too few interactions in a Spock test for a Grails service

I thought I've understood Spock interactions but I have to admin that I'm still missing some pieces of the picture. 我以为我已经了解了Spock的交互方式,但是我不得不管理我仍然缺少一些图片。

Alright, here my problem: I have a method in a Grails service which performs some operations, including a call to a void method of the same service class. 好的,这是我的问题:我在Grails服务中有一个方法可以执行一些操作,包括对同一服务类的void方法的调用。 Here's the code: 这是代码:

class myService {
    void myStuff(def myObj, params) {
        // do my stuff

        anotherMethod(myObj)

        //do my stuff again
    }

    void anotherMethod(myObj) {
        // do other stuff
    }
}

I want to be sure that myStuff method calls anotherMethod, to test and document the correct behaviour. 我想确保myStuff方法调用anotherMethod,以测试和记录正确的行为。

So, here's the test in my Spock Specification class: 因此,这是我的Spock Specification类中的测试:

void 'test myStuff method'() {
    given: 'my object and some params'    
        // doesn't really matter what I'm doing here
        MyObject myObj = new MyObject()
        params = [title: 'my object']

    when: 'we call myStuff()'
        service.myStuff(myObj, params)

    then: 'anotherMethod() is called exactly one times'
        1 * service.anotherMethod(myObj)
    }
}

The error I get is: 我得到的错误是:

Too few invocations for:

1 * service.anotherMethod(myObj)   (0 invocations)

What do you think? 你怎么看? What's wrong? 怎么了?

As always, thanks in advance. 一如既往,在此先感谢。

You are asking for a very special, and generally discouraged, form of mock called partial mocking where methods on the class under test are mocked. 您正在要求一种非常特殊且通常不鼓励使用的模拟形式,称为部分模拟,其中模拟了被测类上的方法。 Spock supports this since 0.7, but you'll have to create a Spy() rather than a Mock() . Spock从0.7开始就支持此功能,但是您必须创建Spy()而不是Mock() Also note that you cannot mock private methods. 还要注意,您不能模拟私有方法。 For more information on spies, see the reference documentation . 有关间谍的更多信息,请参见参考文档

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

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