Friday, 11 May 2018

The Four Types of Test Double: Dummy, Stub, Fake, Mock

A test double is a pretend object used in place of a real object for testing purposes. The four types of test double are as follows:

Dummy

  • An object that is passed around but never used.
  • Used to help fill parameter lists or fulfil mandatory field requirements where the object will never get used but gets the code to run.
  • In many cases it's just an empty or null object.

Stub

  • An object that always returns the same canned response.
  • Used when you want to replace a real implementation with an object that will return the same response every time.

Fake

  • An actual working implementation (close to but not of production quality or configuration) that can replace the real implementation.
  • Can be seen as an enhanced stub that almost does the same work as the production code but takes a few shortcuts in order to fulfil the testing requirements.
  • An example is an in-memory database (used instead of a real, persistent database).

Mock

  • An object that represents a series of expectations and provides canned responses.
  • Can be seen as a programmable stub which can be told the sequence of calls to expect and how it should respond to each one.
  • Combines well with Dependency Injection in that it allows pretend objects to be injected that will behave in precisely known ways.

(Source: The Well-Grounded Java Developer, by Benjamin J. Evans and Martijn Verburg)