xUnit Test Patterns: Test Double Patterns
Patterns in This Chapter
- Test Double
- Test Double Usage
- Test Stub
- Test Spy
- Mock Object
- Fake Object
- Test Double Construction
- Configurable Test Double
- Hard-Coded Test Double
- Test-Specific Subclass
Test Double
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.”
Sometimes it is just plain hard to test the SUT because it depends on other components that cannot be used in the test environment. Such a situation may arise because those components aren’t available, because 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 over or visibility of the internal behavior of the SUT.
When we are writing a test in which we cannot (or choose 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 DOC so that the SUT thinks it is the real one!
How It Works
When the producers of a movie want 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. The stunt double may not be able to act, but he or she knows how to fall from great heights, crash a car, or do 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 the actor’s 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 , 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 variation of Test Double we choose to use, we must keep in mind that we don’t need to implement the entire interface of the DOC. Instead, we provide only the functionality needed for our particular test. We can even build different Test Doubles for different tests that involve the same DOC.
When to Use It
We might want to use some sort of Test Double during our tests in the following circumstances:
- If we have an Untested Requirement (see Production Bugs) because neither the SUT nor its DOCs provide an observation point for the SUT’s indirect output that we need to verify using Behavior Verification
- If we have Untested Code (see Production Bugs) and a DOC does not provide the control point to allow us to exercise the SUT with the necessary indirect inputs
- If we have Slow Tests and we want to be able to run our tests more quickly and hence more often
Each of these scenarios can be addressed in some way by using a Test Double. Of course, we have to be careful when using Test Doubles because we are testing the SUT in a different configuration from the one that will be used in production. For this reason, we really should have at least one test that verifies the SUT 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 because that practice can result in tests that test the wrong software! Also, excessive use of Test Doubles can result in Fragile Tests as a result of Overspecified Software.
Test Doubles come in several major flavors, as summarized in Figure 23.1. The implementation variations of these patterns are described in more detail in the corresponding pattern write-ups.
Figure 23.1 Types of Test Doubles. Dummy Objects are really an alternative to the value patterns. Test Stubs are used to verify indirect inputs; Test Spies and Mock Objects are used to verify indirect outputs. Fake objects provide an alternative implementation.
These variations are classified based on how/why we use the Test Double. We will deal with variations around how we build the Test Doubles in the “Implementation” section.
Variation: Test Stub
We use a Test Stub 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. Its inclusion allows the test to force the SUT down paths it might not otherwise execute. We can further classify Test Stubs by the kind of indirect inputs they are used to inject into the SUT. A Responder (see Test Stub) injects valid values, while a Saboteur (see Test Stub) injects errors or exceptions.
Some people use the term “test stub” to mean a temporary implementation that is used only until the real object or procedure becomes available. I prefer to call this usage 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 , as an observation point for the indirect outputs of the SUT. Like a Test Stub, a Test Spy may need to provide values to the SUT in response to method calls. The Test Spy, however, also captures the indirect outputs of the SUT as it is exercised and saves them for later verification by the test. Thus, in many ways, the Test Spy is “just a” Test Stub with some recording capability. While a Test Spy is used for the same fundamental purpose as a Mock Object , 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 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[1] is on the verification of the indirect outputs. Therefore, a Mock Object is a lot more than just a Test Stub plus assertions: It is used in a fundamentally different way.
Variation: Fake Object
We use a Fake Object 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, a Fake Object implements the same functionality as the real DOC but in a much simpler way. While a Fake Object is typically built specifically for testing, the test does not use it as either a control point or an observation point.
The most common reason for using a Fake Object is that the real DOC 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” describes how we encapsulated all database access behind a persistence layer interface and then replaced the database with in-memory hash tables and made our tests run 50 times faster. Chapter 6, Test Automation Strategy, and Chapter 11, 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 cares about these objects, we may choose to pass in a Dummy Object, 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). In this sense, a Dummy Object isn’t really a Test Double per se but rather an alternative to the value patterns Literal Value, Derived Value, and Generated Value.
Variation: Procedural Test Stub
A Test Double implemented in a procedural programming language is often called a “test stub,” but I prefer to call it a Procedural Test Stub (see Test Stub) to distinguish this usage from the modern Test Stub variation of Test Doubles. Typically, we use a Procedural Test Stub to allow testing/debugging to proceed while waiting for other code to become available. It is rare for these objects to be “swapped in” at runtime but sometimes we make the code conditional on a “Debugging” flag—a form of Test Logic in Production.
Implementation Notes
Several considerations must be taken into account when we are building the Test Double (Figure 23.2):
- Whether the Test Double should be specific to a single test or reusable across many tests
- Whether the Test Double should exist in code or be generated on-the-fly
- How we tell the SUT to use the Test Double (installation)
The first and last points are addressed here. The discussion of Test Double generation is left to the section on Configurable Test Doubles.
Because the techniques for building 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 into separate patterns.
Figure 23.2 Types of Test Doubles with implementation choices. Only Test Stubs, Test Spies, and Mock Objects need to be hard-coded or configured by the test. Dummy Objects have no implementation; Fake Objects are installed but not controlled by the test.
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 “real” implementation. Fake Objects, by contrast, need a “real” implementation but one that is much simpler or “lighter” than the object that 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 it as if it were real.
Variation: Hard-Coded Test Double
When we plan to use a specific Test Double in only 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 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 ; and the Test Double implemented as separate Test Double Class (see Hard-Coded Test Double). Each of these options 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 prefer to use a Configurable Test Double. Although the test automater can manually build these objects, many members of the xUnit family have reusable toolkits available for generating Configurable Test Doubles.
Installing the Test Double
Before we can exercise the SUT, we must tell it to use the Test Double instead of the object that the Test Double replaces. We can use any of the substitutable dependency patterns to install the Test Double 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 perform this configuration before we install them.
Example: Test Double
Because there are a wide variety of reasons for using the variations of Test Doubles, it is difficult 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.