Test Double is the generic term for any kind of pretend object used in place of a real object for testing purposes

Test Double Type

Description

Dummy

  • dummy objects are passed around but never actually used
  • usually, they are just used to fill parameter lists.

Fake

  • fake objects actually have working implementations, but usually take some shortcut that makes them not suitable for production
  • behaves exactly the same as their real counterparts
  • an in-memory/embedded database is a fake of a real database

Stub

  • stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test
  • can be used for state verification

Spy

  • records how they were called for behavior verification
  • usually wraps around an existing object
  • used for behavior verification

Mock

  • are pre-programmed with expectations that form a specification of the calls they are expected to receive
  • creates a new object
  • used for
  • can be used for behavior verification

Stub vs Mock - Lifecycle

Test lifecycle with stubs:

  1. Setup - prepare the object that is being tested and its stubs collaborators
  2. Exercise - test the functionality
  3. Verify state - use asserts to check the object’s state
  4. Teardown - clean up resources

Test lifecycle with mocks:

  1. Setup data - prepare the object that is being tested
  2. Setup expectations - prepare expectations in mock that is being used by the primary object
  3. Exercise - test the functionality
  4. Verify expectations - verify those correct methods have been invoked in mock
  5. Verify state - use asserts to check the object’s state
  6. Teardown - clean up resources

Resources