Hosted by:
Unit testing expertise at your fingertips!
Home | Discuss | Lists

Test Double

The book has now been published and the content of this chapter has likely changed substanstially.
Please see page 522 of xUnit Test Patterns for the latest information.
Also known as: Imposter

How can we verify logic independently when code it depends on is unusable?
How can we avoid Slow Tests?

We replace a component on which the SUT depends with a "test-specific equivalent."

Sketch Test Double embedded from Test Double.gif

Sometimes it is just plain hard to test the system under test (SUT) because it depends on other components that cannot be used in the test environment. This could be because they aren't available, they will not return the results needed for the test or because executing them would have undesirable side effects. In other cases, our test strategy requires us to have more control or visibility of the internal behavior of the SUT.

When we are writing a test in which we cannot (or chose not to) use a real depended-on component (DOC), we can replace it with a Test Double. The Test Double doesn't have to behave exactly like the real DOC; it merely has to provide the same API as the real one so that the SUT thinks it is the real one!

How It Works

When the movie industry wants to film something that is potentially risky or dangerous for the leading actor to carry out, they hire a "stunt double" to take the place of the actor in the scene. The stunt double is a highly trained individual who is capable of meeting the specific requirements of the scene. They may not be able to act, but they know how to fall from great heights, crash a car, or whatever the scene calls for. How closely the stunt double needs to resemble the actor depends on the nature of the scene. Usually, things can be arranged such that someone who vaguely resembles the actor in stature can take their place.

For testing purposes, we can replace the real DOC (not the SUT!) with our equivalent of the "stunt double": the Test Double. During the fixture setup phase of our Four-Phase Test (page X), we replace the real DOC with our Test Double. Depending on the kind of test we are executing, we may hard-code the behavior of the Test Double or we may configure it during the setup phase. When the SUT interacts with the Test Double, it won't be aware that it isn't talking to the real McCoy, but we will have achieved our goal of making impossible tests possible.

Regardless of which of the variations of Test Double we choose to use, we must keep in mind that we don't need to implement the whole interface of the DOC. We only provide whatever functionality is needed for our particular test. We can even build different Test Doubles for different tests that involve the same DOC.

When To Use It

There are several different circumstances in which we might want to use some sort of Test Double during our tests.

Each of these can be addressed in some way by using a Test Double. But we have to be careful when using Test Doubles because we are testing the SUT in a different configuration from that which will be used in production. So we really should have at least one test that verifies it works without a Test Double. WE need to be careful that we don't replace the parts of the SUT that we are trying to verify as this can result in tests that test the wrong software! Also, excessive use of Test Doubles can result in Fragile Tests (page X) as a result of Overspecified Software.

Test Doubles come in several main flavors as summarized in the following diagram. The implementation variations of these patterns are described in more detail in the corresponding pattern write-ups.

Sketch Types Of Test Doubles embedded from Types Of Test Doubles.gif

These variations are classified based on how/why we use the Test Double. I'll deal with variations around how we build the Test Doubles in the "Implementation" section below.

Variation: Test Stub

We use a Test Stub (page X) to replace a real component on which the SUT depends so that the test has a control point for the indirect inputs of the SUT. This allows the test to force the SUT down paths it might not otherwise execute

Some people use the term "Test Stub" to mean a temporary implementation that is used only until the real object or procedure is available. I prefer to call this a Temporary Test Stub (see Test Stub) to avoid confusion.

Variation: Test Spy

We can use a more capable version of a Test Stub, the Test Spy (page X), as an observation point for the indirect outputs of the SUT. Like a Test Stub, the Test Spy may need to provide values to the SUT in response to method calls but the Test Spy also captures the indirect outputs of the SUT as it is exercised and saves them for later verification by the test. So in many ways the Test Spy is "just a" Test Stub with some recording capability. While it is used for the same fundamental purpose as a Mock Object (page X), the style of test we write using a Test Spy looks much more like a test written with a Test Stub.

Variation: Mock Object

We can use a Mock Object as an observation point that is used to verify the indirect outputs of the SUT as it is exercised. Typically, the Mock Object also includes the functionality of a Test Stub in that it must return values to the SUT if it hasn't already failed the tests but the emphasis(My mother grew up in Hungary and has retained a part of her Hungarian accent -- think Zsa Zsa Gabor -- all her life. She says "It is important to put the emphasis on the right sylable.") is on the verification of the indirect outputs. Therefore, a Mock Object is lot more than just a Test Stub plus assertions; it is used a fundamentally different way.

Variation: Fake Object

We use a Fake Object (page X) to replace the functionality of a real DOC in a test for reasons other than verification of indirect inputs and outputs of the SUT. Typically, it implements the same functionality as the real DOC but in a much simpler way. While a Fake Object is typically built specifically for testing, it is not used as either a control point or a observation point by the test.

The most common reason for using a Fake Object is that the real depended-on component is not available yet, is too slow or cannot be used in the test environment because of deleterious side effects. the sidebar Faster Tests Without Shared Fixtures (page X) describes how we encapsulated all database access behind a persistence layer interface and them replaced the database with in-memory hash tables and made our tests run 50 times faster. Chapters Test Automation Strategy and Using Test Doubles provide an overview of the various techniques available for making our SUT easier to test.

Variation: Dummy Object

Some method signatures of the SUT may require objects as parameters. If neither the test nor the SUT care about these objects, we may choose to pass in a Dummy Object (page X) which may be as simple as a null object reference, an instance of the Object class or an instance of a Pseudo Object (see Hard-Coded Test Double on page X). In this sense, a Dummy Object isn't really a Test Double per se but rather an alternative to the value patterns Literal Value (page X), Derived Value (page X) and Generated Value (page X).

Variation: Procedural Test Stub

A Test Double implemented in a procedural programming language is often called a "Test Stub" but I prefer to call them a Procedural Test Stub (see Test Stub) to distinguish them from the modern Test Stub variation of Test Doubles. Typically, we use them to allow testing/debugging to proceed while waiting for other code to become available. It is rare for them to be "swapped in" at runtime but sometimes we make the code conditional on a "Debugging" flag, a form of Test Logic in Production (page X).

Implementation Notes

There are several considerations when we are building the Test Double. These include:

I'll address the first and last points here and leave the discussion about Test Double generation to the section on Configurable Test Doubles below.

Because the techniques for building the Test Doubles are pretty much independent of their behavior (e.g. they apply to both Test Stubs and Mock Objects), I've chosen to split out the descriptions of the various ways we can build Hard-Coded Test Doubles and Configurable Test Doubles (page X) into separate patterns and I've just included a brief summary here.

Variation: Unconfigurable Test Doubles

Neither Dummy Objects nor Fake Objects need to be configured each for their own reason. Dummies should never be used by the receiver so they need no implementation. Fake Objects, on the other hand, need a "real" implementation but one which is much simpler or "lighter" than the object which they replace. Therefore, neither the test nor the test automater will need to configure "canned" responses or expectations; we just install the Test Double and let the SUT use them as if they were real.

Variation: Hard-Coded Test Double

When we only plan to use a specific Test Double in a single test, it is often simplest to just hard-code the Test Double to return specific values (for Test Stubs) or expect specific method calls (Mock Objects.) Hard-Coded Test Doubles are typically hand-built by the test automater. They come in several forms including the Self Shunt (see Hard-Coded Test Double) (where the Testcase Class (page X) acts as the Test Double), the Anonymous Inner Test Double (see Hard-Coded Test Double) (where language features are used to create the Test Double inside the Test Method (page X)) and a Test Double implemented as separate Test Double Class (see Hard-Coded Test Double). Each of these is discussed in more detail in Hard-Coded Test Double

Variation: Configurable Test Double

When we want to use the same Test Double implementation in many tests, we will typically want to use a Configurable Test Double. These can also be hand-built by the test automater but many members of the xUnit family have reusable toolkits available for generating test doubles.

Installing the Test Double

Before the SUT can be exercised, we must tell the SUT to use the Test Double instead of the object it replaces. We can use any of the substitutable dependency patterns to install it during the fixture setup phase of our Four-Phase Test. Configurable Test Doubles need to be configured before we exercise the SUT and we typically do this before we install them.

Example: Test Double

Because there are a wide variety of reasons for using the variations of Test Double it is hard to provide a single example that characterizes the motivation behind each style. Please refer to the examples in each of the more detailed patterns referenced earlier.

Page generated at Wed Feb 09 16:39:43 +1100 2011

Copyright © 2003-2008 Gerard Meszaros all rights reserved

All Categories
Introductory Narratives
Web Site Instructions
Code Refactorings
Database Patterns
DfT Patterns
External Patterns
Fixture Setup Patterns
Fixture Teardown Patterns
Front Matter
Result Verification Patterns
Test Double Patterns
Test Organization
Test Refactorings
Test Smells
Test Strategy
Value Patterns
XUnit Basics
xUnit Members
All "Test Double Patterns"
Test Double
--Test Stub
--Test Spy
--Mock Object
--Fake Object
--Configurable Test Double
--Hard-Coded Test Double
Test-Specific Subclass