groovy - Spock框架: what is the purpose of Spies vs.使用真实对象还是模拟?

标签 groovy spock

来自文档:

A spy is always based on a real object. Hence you must provide a class type rather than an interface type, along with any constructor arguments for the type. If no constructor arguments are provided, the type’s default constructor will be used.

Method calls on a spy are automatically delegated to the real object. Likewise, values returned from the real object’s methods are passed back to the caller via the spy.

另外:

When stubbing a method on a spy, the real method no longer gets called:

subscriber.receive(_)>>“确定”

Instead of calling SubscriberImpl.receive, the receive method will now simply return "ok".

如果 spy 只是真实对象和调用者之间的接口(interface)层,为什么不直接使用真实对象呢?使用 spy 可以提供什么而使用真实对象或模拟则不能提供?

对我来说,它似乎处于模拟对象和真实对象之间的空白中。

最佳答案

spy 可以在不同的场景中使用。但是,如果您可以在不借助 spy 的情况下实现测试,那就太好了。

(Think twice before using this feature. It might be better to change the design of the code under specification.)

  1. 它们可用于验证方法是否被调用,而无需模拟方法本身
  2. 您可以取消不想发生的调用
  3. 您可以使用部分模拟来测试对象本身

    // this is now the object under specification, not a collaborator
    def persister = Spy(MessagePersister) {
      // stub a call on the same object
      isPersistable(_) >> true
    }

    when:
    persister.receive("msg")

    then:
    // demand a call on the same object
    1 * persister.persist("msg")

示例和引用来自文档@ http://spockframework.org/spock/docs/1.1/all_in_one.html#Spies

关于groovy - Spock框架: what is the purpose of Spies vs.使用真实对象还是模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45282252/

相关文章:

grails - 在这种情况下,如何确定域模型?

inheritance - Jenkins groovy 管道简单继承故障

elasticsearch - 如何在 Elasticsearch 脚本中访问嵌套数组的文档值?

grails - Spock Test,只检查方法是否被调用,不执行

unit-testing - 无法为类 LoginService 创建模拟。非接口(interface)类型的模拟需要 CGLIB 库..?

testing - Grails 不能使用 Spock 框架?

grails - 如何在gsp/groovy中获取检查项目

java - 我能否找到可能在 Groovy 代码块中抛出的所有(已检查)异常?

grails - geb.env和geb.driver之间的区别

grails - 使用 NonEmptyNavigator.metaClass.invokeMethod { ... } 在字段设置后引入短暂的暂停