Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active December 14, 2020 00:35
Show Gist options
  • Save rpivo/7f3c743718a899d1731119a993666e61 to your computer and use it in GitHub Desktop.
Save rpivo/7f3c743718a899d1731119a993666e61 to your computer and use it in GitHub Desktop.
Gerard Meszaros' Test Double Definitions

Gerard Meszaros' Test Double Definitions

Martin Fowler wrote a great blog article called Mocks Aren't Stubs, and in it he describes some of Gerard Meszaros' test double definitions. Here's a quote:

  • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
  • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
  • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed [...] for the test.
  • Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent.
  • Mocks are [...] objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

When first being introduced to testing, it's easy to be overwhelmed with some of these new words, and it's easy to struggle in distinguishing one kind of test double from another, but Fowler & Meszaros' definitions here are really great.

Even so, I find that the definitions for fake, stub, and mock are all close enough that they can still be confused with each other.

To me, a stub replaces a callable variable with just a return value, or maybe a no-op of some kind. Any side effects that could occur in the original callable value would likely be absent from the stub. A stub can be used to get a "canned answer", or to void some internally called function inside a parent mock that you're setting up.

As far as spies go, modern JavaScript testing suites will allow you to spy on some functionality, which doesn't disrupt the original characteristics or usage necessarily, but allows you to see the ways in which it was accessed or called.

A mock is useful when you want to make a function or class actually usable within a test, typically with a specific internal state in place for the given test. This oftentimes requires you to set up some or even all of the original API.

This sounds a bit different from the definition of fake above. Maybe a fake is kind of like a mock, but perhaps a lot of the internals are stubbed or non-existent. There is a lot of possible nuance here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment