来自文档:
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.)
- 它们可用于验证方法是否被调用,而无需模拟方法本身
- 您可以取消不想发生的调用
- 您可以使用部分模拟来测试对象本身
// 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/