Programming ≈ Fun

Written by Krešimir Bojčić

Mocking and Stubbing On Tiny Example

Guard Clause

If you know what test doubles are. If you know that stub gives canned answers and that mock is an object that you can set expectations on… Pass along. If you are still uncertain about this you may want to read on.


Chances are (if you are a guy) that you are using stub when talking to your girlfriend:

Does my ass look big in this jeans? No!

It doesn’t matter what the real answer is, you just give back the prepared one. Kinda like when you need certain data for your tests. You shove in your answer for example 11/28/2011 and you expect the canned answer every time. It’s a lie agreed upon for the greater cause.


Mock is emotionally ‘complicated’ stub. He also gives back canned answers but he expects certain things to be done in the process to be fully satisfied. Translated to our girlfriend example it is something like this:

Are you cheating on me? No!

Here the expectation is that you don’t give answer right away, because it looks canned that way. Also you shouldn’t think to long before answering. Mocked object v2.0 might expect that you look her in the eyes…

DRY me is noticing that we have overlapping in code, so I would probably use the same algorithm for both question in the class BlowTheTruthOutOfWaterIfItsBrutal.

Why Would I Mock/Stub Anyway

  1. You don’t have the collaborator object when TDD-ing feature
  2. Collaborator is slow
  3. Collaborator is ‘outside’ component
  4. You want to isolate your tests more
  5. You want canned answers (time travel for example)


You have a green tests and non working application when stub/mock is not mimicking the real collaborator good enough. It makes you look pretty stupid, so watch out for this!