Mock() vs Spy() vs Stub() 之间的 Spock 区别

Spock difference between Mock() vs Spy() vs Stub()

虽然 this question 已经回答了,但我仍然不清楚在模拟期间我应该使用哪个

同时参考spock.lang.MockingApi.java。我无法捕捉到这些之间的任何区别。

Mock的文档说

Person person = Mock() // type is Person.class, name is "person"

Spy 的文档说

Person person = Spy() // type is Person.class, name is "person"

Stub 的文档说

Person person = Stub() // type is Person.class, name is "person"

这清楚地表明它们之间没有任何区别。那么,为什么我们要采用这三种模拟策略,以及使用它们和何时使用它们之间究竟有什么区别。

如果是带有示例代码的答案,那将非常有帮助。

来自 https://github.com/spockframework/spock/blob/master/docs/interaction_based_testing.adoc

Stubbing is the act of making collaborators respond to method calls in a certain way. When stubbing a method, you don’t care if and how many times the method is going to be called; you just want it to return some value, or perform some side effect, whenever it gets called.

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. 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.