Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Although this question was already answered, still I'm not clear which one should I use during mocking

While referring to spock.lang.MockingApi.java. I couldn't able to catch any difference between any of these.

The documentation for Mockis saying

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

The documentation for Spy is saying

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

The documentation for Stub is saying

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

which is clearly stating that there is no difference between any of these. So why we having these three mocking strategy in place and what exactly the difference between then and when to use them.

It would be much helpful, if it is an answer with sample code.

like image 607
Suganthan Madhavan Pillai Avatar asked May 12 '16 00:05

Suganthan Madhavan Pillai


1 Answers

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

like image 187
Alex K. Avatar answered Nov 09 '22 23:11

Alex K.