Update 2017-02-06: Actually user mikhail's answer is more specific to Spock than my original one above. So within the scope of Spock, what he describes is correct, but that does not falsify my general answer:
subscriber.receive(_) >> "ok" // subscriber is a Stub()
Mock: < em > 用于描述规范下的对象与其协作者之间的交互。
def "should send message to subscriber"() {
when:
publisher.send("hello")
then:
1 * subscriber.receive("hello") // subscriber is a Mock()
}
Mock 可以充当 Mock 和 Stub:
1 * subscriber.receive("message1") >> "ok" // subscriber is a Mock()
Spy: < em > 总是基于一个实际的对象,使用原始的方法来做实际的事情。可以像 Stub 一样用于更改选择方法的返回值。可以像 Mock 一样用于描述交互。
def subscriber = Spy(SubscriberImpl, constructorArgs: ["Fred"])
def "should send message to subscriber"() {
when:
publisher.send("hello")
then:
1 * subscriber.receive("message1") >> "ok" // subscriber is a Spy(), used as a Mock an Stub
}
def "should send message to subscriber (actually handle 'receive')"() {
when:
publisher.send("hello")
then:
1 * subscriber.receive("message1") // subscriber is a Spy(), used as a Mock, uses real 'receive' function
}
Stubs are really only to facilitate the unit test, they are not part of the test. Mocks, are part of the test, part of the verification, part of the pass / fail.