A common issue when writing tests for real-world software is how to deal with third-party dependencies. Let’s examine an old, but counter-intuitive principle.
Once upon a time, I made a stupid joke on Twitter about the Don’t Mock What You Don’t Own testing principle:
Only mock what you own, because mocking others is rude. — Yours Truly , Tweet
While it didn’t get me fired, it led to me being tricked into giving a 5 minute-long talk about it. Given the confused replies I got to the joke Tweet, I’ve decided it’s worth writing down the contents of the talk for posterity.
The principle
Don’t Mock What You Don’t Own means that whenever you employ mock objects, you should use them to substitute your own objects and not third-party ones.
If you’re anything like me, that makes no sense! What else am I supposed to mock? My code is perfectly testable!
Key point: there’s a difference between owning an object and owning the API to use it.
Allow me to use a simple example to demonstrate the downsides of mocking third-party objects and what to do instead.
Disclaimer: I don’t like mocks in the original sense: a test object, that mimics another (usually complex) object, records calls to its APIs, and allows you to make assertions over those calls. However, this principle is still useful, because it applies equally to any other type of test object. I will keep using the term mock throughout this article to remain congruent with the name of the principle and I will be using a popular mocking library in my examples for familiarity. However, I don’t use mocks in my own code at all. In Python I use pretend for simple stubs and verified fakes for more complex scenarios. In Go I reach always for verified fakes. This isn’t potayto potahto – this is a fundamental difference in how to approach testing, but it’s out of scope for this article. If you’re confused by the differences between mocks, fakes, stubs, et cetera, I recommend Martin Fowler’s Mocks Aren’t Stubs.
... continue reading