Headshot-color me@jbrains.ca Find out where I'm appearing

When to fake; when to mock

I originally published this on January 3, 2005. One of my other postings links to this article, so I wanted to bring it back to life. Thanks to James Breen for pointing out the broken link to me.

In working with Pat Welsh I had occasion to describe in a rather pithy way when to fake and when to mock, so I thought I’d share that with you.

To be clear, I mean “mock” in the sense of interaction-based testing with mock objects, and I mean “fake” in the sense of state-based testing with fakes or stubs. Google if you need a stronger definition of those terms, but they suit me for now.

Note that I use the term “stub” when I used to say “fake”.

So then, I want to test some object in isolation from the rest of the system. In broad terms, I need to write tests to answer two essential questions:

  1. Am I using the objects around me correctly? Am I invoking the right methods at the right times with the right parameters?
  2. Am I reacting to the objects around me correctly? Do I handle errors reasonably? Do I respond well to the answers they send me?

For the first kind of test, I generally mock; and for the second kind of test, I generally fake.

Put another way, I lean on interaction-based testing to verify how my object talks to its collaborators; but I lean on state-based testing to verify how well that object listens.

blog comments powered by Disqus