Spies and Stubs

I was reading this article which is a response to an email from a person liking mocks but disliking spies. Before starting to read I was confused since I personally dislike mocks and spies sounded even worse. However it turned out I was wrong.
I was wrong because I have obviously been shielded from the JavaScript world well enough to not know that spies are the same things as stubs. Now I suddenly became even more confused. Why would anybody dislike stubs and prefer mocks over stubs?

Before we move on we need to make sure we talk about the same things. This is a topic I covered a long time ago but the essence is; Stubs respond with a small number of well known values (often only one) regardless of state while mocks know how and when they will be called.

So why do I dislike mocks? It's because of the Spiderman (or Pippi Longstocking if you prefer)! In order to make it easy to create test doubles people like using what is often called "mock frameworks". Most of these frameworks have functionality to actually function as mocks as per the definition above. Since mocking is actually one of the most complex forms of test doubling creators of mock frameworks like to show off that functionality leading to beginners thinking that is the right pattern to use everywhere. The pattern I refer to is verifying behavior through expectations. And suddenly the poor bastard trying to learn TDD/BDD is creating tests that are hard to maintain because the tests know too much about implementation detail! Remember Spider man! With great powers comes great responsibilities!

Stubs directly inherit the problem of pushing you towards expectation verification but rather is just a helpful tool. And remember that all mock frameworks typically also work just fine as stub frameworks too! And a stub can easily be converted into verifying expectations when needed!

So back to confusion; I must say that I find "spies" a terrible name for something others call "stubs" since to me spying implies you look at something you are not supposed to look like. Like the PrivateObject in .NET. And from reading the article I originally linked in this article I think it looks like the original writer worked on a team where spies was used as mocks the same way stubs can be turned into mocks. Because the important thing is not if you use a mock or stub object but if you are using a stub or mock pattern in your test double. 

One thing that the article linked above is really good at pointing out is that when in doubt; use stubs for queries and mocks for actions. But there is another important lesson in there too! Whenever your test starts to get a complex setup you often lack a level of abstraction. And that is more important that stubs vs mocks in my opinion!

No comments:

Post a Comment