lunedì 4 luglio 2011

Mocks and Stubs

What's  the difference?

I found a very interesting post on this argument Mocks Aren't Stubs

reading the post I have learned that Stubs use state verification while Mocks use behaviour verification.

In few words:

  • with a mock you expect your class calls some mock object methods which in turn will return a particular data, what you'll check is that the class under test will really call those methods.
  • With a stub, you implement the real object methods your test will use, naturally the implementation will be very easy. Than you'll check the state of the stub is what you expect (so you need to write some extra methods to access stub instance variables). Stubs may also record information about calls.

I also learned that classical TDD style uses real objects as much as possible and a Test Double only if it's awkward to use the real ones while a mockist TDD style will always use a mock for all objects except the one under test.


Another couple of things:

  • A Test Double is a generic term used for any kind of object used to replace the real one for testing purposes.
  • Types of Test Doubles, other than stubs and Mock,s are Dummy objects that are passed around but never actually used, usually they are used just to fill parameter lists. Fake objects that have an implementation not suitable for production.