Using Test Doubles
About This Chapter
The last few chapters concluding with Chapter 10 , Result Verification, introduced the basic mechanisms of running tests using the xUnit family of Test Automation Frameworks (page 298 ). For the most part we assumed that the SUT was designed such that it could be tested easily in isolation of other pieces of software. When a class does not depend on any other classes, testing it is relatively straightforward and the techniques described in this chapter are unnecessary. When a class does depend on other classes, we have two choices: We can test it together with all the other classes it depends on or we can try to isolate it from the other classes so that we can test it by itself. This chapter introduces techniques for isolating the SUT from the other software components on which it depends.
What Are Indirect Inputs and Outputs?
The problem with testing classes in groups or clusters is that it becomes very hard to cover all the paths through the code. The depended-on component (DOC) may return values or throw exceptions that affect the behavior of the SUT, but it may prove difficult or impossible to cause certain cases to occur. The indirect inputs received from the DOC may be unpredictable (such as the system clock or calendar). In other cases, the DOC may not be available in the test environment or may not even exist. How can we test dependent classes in these circumstances?
In other cases, we need to verify that certain side effects of executing the SUT have, indeed, occurred. If it is too difficult to monitor these indirect outputs of the SUT (or if it is too expensive to retrieve them), the effectiveness of our automated testing may be compromised.
As you will no doubt have guessed from the title of this chapter, the solution to these problems is often the use of a Test Double (page 522 ). We will start by looking at how we can use Test Doubles to test indirect inputs and outputs. We will then describe a few other uses of these helpful mechanisms.
Why Do We Care about Indirect Inputs?
Calls to DOCs often return objects or values, update their arguments or even throw exceptions. Many of the execution paths within the SUT are intended to deal with these return values and to handle the possible exceptions. Leaving these paths untested leads to Untested Code (see Production Bugs on page 268 ). These paths can be the most challenging to test effectively but are also among the most likely to lead to catastrophic failures if exercised for the very first time in production.
We certainly would rather not have the exception-handling code execute for the first time in production. What if it was coded incorrectly? Clearly, it would be highly desirable to have automated tests for such code. The testing challenge is to somehow cause the DOC to throw an exception so that the error path can be tested. The exception we expect the DOC to throw is a good example of an indirect input test condition ( Figure 11.1 ). Our means of injecting this input is a control point .
Figure 11.1. An indirect input being received by the SUT from a DOC. Not all inputs of the SUT come from the test. Some indirect inputs come from other components called by the SUT in the form of return values, updated parameters, or exceptions thrown.
Why Do We Care about Indirect Outputs?
The concept of encapsulation often directs us to not care about how something is implemented. After all, that is the whole purpose of encapsulation—to alleviate the need for clients of our interface to care about our implementation. When testing, we try to verify the implementation precisely so our clients do not have to care about it.
Consider for a moment a component that has a method in its API that returns nothing—or at least nothing that can be used to determine whether it has performed its function correctly. In this situation, we have no choice but to test through the back door. A good example of this is a message logging system. Calls to the API of a logger rarely return anything that indicates it did its job correctly. The only way to determine whether the message logging system is working as expected is to interact with it through some other interface—one that allows us to retrieve the logged messages.
A client of the logger may specify that the logger be called when certain conditions are met. These calls will not be visible on the client's interface but would typically be a requirement that the client needs to satisfy and, therefore, would be something we want to test. The circumstances that should result in a messaging being logged are indirect output test conditions ( Figure 11.2 ) for which we need to write tests so that we can avoid having Untested Requirements (see Production Bugs ). Our means of seeing this output is an observation point .
Figure 11.2. An indirect output being received by the SUT. Not all outputs of the SUT are directly visible to the test. Some indirect outputs are sent to other components in the form of method calls or messages.
In other cases, the SUT does produce visible behavior that can be verified through the front door but also has some expected side effects. Both outputs need to be verified in our tests. Sometimes this testing is simply a matter of adding assertions for the indirect outputs to the existing tests to verify the Untested Requirement .
How Do We Control Indirect Inputs?
Testing with indirect inputs is a bit simpler than testing with indirect outputs because the techniques used to test outputs build on those used to test inputs. Let's delve into indirect inputs first.
To test the SUT with indirect inputs, we must be able to control the DOC well enough to cause it to return every possible kind of return value. That implies the availability of a suitable control point.
Examples of the kinds of indirect inputs we want to be able to induce via this control point include
- Return values of methods/functions
- Values of updatable arguments
- Exceptions that could be thrown
Often, the test can interact with the DOC to set up how it will respond to requests. For example, if a component provides access to data in a database, then we can use Back Door Setup (see Back Door Manipulation on page 327 ) to insert specific values into a database that cause the component to respond in the desired ways (e.g., no items found, one item found, many items found). (See Figure 11.3 .) In this specific case, we can use the database itself as a control point.
Figure 11.3. Using Back Door Manipulation to indirectly control and observe the SUT. When the SUT stores its state in another component, we may be able to manipulate that state by having the test interact directly with the other component via a "back door."
In most cases, however, this approach is neither practical nor even possible. We might not be able to use the real component for the following reasons:
- The real component cannot be manipulated to produce the desired indirect input. Only a true software error within the real component would result in the desired input to the SUT.
- The real component could be manipulated to make the input occur but doing so would not be cost-effective.
- The real component could be manipulated to make the input occur but doing so could have unacceptable side effects.
- The real component is not yet available for use.
If we cannot use the real component as a control point, then we have to replace it with one that we can control. This replacement can be done in a number of different ways, which are the focus of the section Installing the Test Double later in this chapter. The most common approach is to configure a Test Stub (page 529 ) with a set of values to return from its functions and then to install this Test Stub into the SUT. During execution of the SUT, the Test Stub receives the calls and returns the previously configured responses ( Figure 11.4 ). It has become our control point.
Figure 11.4. Using a Test Stub as a control point for indirect inputs. One way to use a control point to inject indirect inputs into the SUT is to install a Test Stub in place of the DOC. Before exercising the SUT, we tell the Test Stub what it should return to the SUT when it is called. This strategy allows us to force the SUT through all its code paths.
How Do We Verify Indirect Outputs?
In normal usage, as the SUT is exercised, it interacts naturally with the component(s) upon which it depends. To test the indirect outputs, we must be able to observe the calls that the SUT makes to the API of the DOC ( Figure 11.5 ). Furthermore, if we need the test to progress beyond that point, we need to be able to control the values returned (as was discussed in the discussion of indirect inputs).
Figure 11.5. Using Behavior Verification to verify the indirect outputs of the SUT. When we care about exactly what calls our SUT makes to other components, we may have to do Behavior Verification rather than simply verifying the post-test state of the SUT.
In many cases, the test can use the DOC as an observation point to find out how it has been used. For example:
- We can ask the file system for the contents of a file that the SUT has written to verify that it exists and was written with the expected contents.
- We can ask the database for the contents of a table or specific record to verify that the SUT wrote the expected records to the database.
- We can interact directly with the e-mail sending component to ask whether the SUT had asked it to send a particular e-mail.
These are all examples of Back Door Verification (see Back Door Manipulation on page 327 ). Some DOCs allow us to configure their behavior in such a way that we can use them to keep the test informed of how they are being used:
- We can ask the file system to notify the test whenever a file is created or modified so we can verify its contents.
- We can use a database trigger to notify the test when a record is written or deleted.
- We can configure the e-mail sending component to deliver all outgoing e-mail to the test.
Sometimes, as we have seen with indirect inputs, it is not practical to use the real component as an observation point. When all else fails, we may need to replace the real component with a test-specific alternative. For example, we might need to do this for the following reasons:
- The calls to (or the internal state of) the DOC cannot be queried.
- The real component can be queried but doing so is cost-prohibitive.
- The real component can be queried but doing so has unacceptable side effects.
- The real component is not yet available for use.
The replacement of the real component can be done in a number of different ways, as will be discussed in Installing the Test Double .
Two basic styles of indirect output verification are available. Procedural Behavior Verification (see Behavior Verification ) captures the calls to a DOC (or their results) during SUT execution and then compares them with the expected calls after the SUT has finished executing. This verification involves replacing a substitutable dependency with a Test Spy (page 538 ). During execution of the SUT, the Test Spy receives the calls and records them. After the Test Method (page 348 ) has finished exercising the SUT, it retrieves the actual calls from the Test Spy and uses Assertion Methods (page 362 ) to compare them with the expected calls ( Figure 11.6 ) .
Figure 11.6. Using a Test Spy as an observation point for indirect outputs of the SUT. One way to implement Behavior Verification is to install a Test Spy in place of the target of the indirect outputs. After exercising the SUT, the test asks the Test Spy for information about how it was used and compares that information to the expected behavior using assertions.
Expected Behavior ( see Behavior Verification ) involves building a "behavior specification" during the fixture setup phase of the test and then comparing the actual behavior with this Expected Behavior . It is typically done by loading a Mock Object (page 544 ) with a set of expected procedure call descriptions and installing this object into the SUT ( Figure 11.7 ). During execution of the SUT, the Mock Object receives the calls and compares them to the previously defined expected calls (the "behavior specification"). As the test proceeds, if the Mock Object receives an unexpected call, it fails the test immediately. The test failure traceback will show the exact location in the SUT where the problem occurred because the Assertion Methods are called from the Mock Object, which is in turn called by the SUT. We can also see exactly where in the Test Method the SUT was being exercised.
Figure 11.7. Using a Mock Object as an observation point for indirect outputs of the SUT. Another way to implement Behavior Verification is to install a Mock Object in place of the target of the indirect outputs. As the SUT makes calls to the DOC, the Mock Object uses assertions to compare the actual calls and arguments with the expected calls and arguments.
When we use a Test Spy or a Mock Object , we may also have to employ it as a control point for any indirect inputs on which the SUT depends after the Test Spy or Mock Object has been called to allow test execution to continue.
Testing with Doubles
By now you are probably wondering about how to replace those inflexible and uncooperative real components with something that makes it easier to control the indirect inputs and to verify the indirect outputs.
As we have seen, to test the indirect inputs, we must be able to control the DOC well enough to cause it to return every possible kind of return value (valid, invalid, and exception). To test indirect outputs, we must be able to track the calls the SUT makes to other components. A Test Double is a type of object that is much more cooperative and lets us write tests the way we want to.
Types of Test Doubles
A Test Double is any object or component that we install in place of the real component for the express purpose of running a test. Depending on the reason why we are using it, a Test Double can behave in one of four ways (summarized in Figure 11.8 ):
- A Dummy Object (page 728 ) is a placeholder object that is passed to the SUT as an argument (or an attribute of an argument) but is never actually used.
- A Test Stub is an object that replaces a real component on which the SUT depends so that the test can control the indirect inputs of the SUT. It allows the test to force the SUT down paths it might not otherwise exercise. A Test Spy, which is a more capable version of a Test Stub , can be used to verify the indirect outputs of the SUT by giving the test a way to inspect them after exercising the SUT.
- A Mock Object is an object that replaces a real component on which the SUT depends so that the test can verify its indirect outputs.
- A Fake Object (page 551 ) (or just "Fake" for short) is an object that replaces the functionality of the real DOC with an alternative implementation of the same functionality.
Figure 11.8. Several kinds of Test Doubles exist. 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 emulate the behavior of the real depended-on component, but with test-friendly characteristics.
Dummy Objects
Dummy Objects are a degenerate form of Test Double . They exist solely so that they can be passed around from method to method; they are never used. That is, Dummy Objects are not expected to do anything except exist. Often, we can get away with using "null" (or "nil" or "nothing"); at other times, we may be forced to create a real object because the code expects something non-null. In dynamically typed languages, almost any real object will do; in statically typed languages, we must make sure that the Dummy Object is "type-compatible" with the parameter it is being passed as or the variable to which it is being assigned.
In the following example, we pass an instance of DummyCustomer to the Invoice constructor to satisfy a mandatory argument. We do not expect the DummyCustomer to be used by the code we are testing here.
public void testInvoice_addLineItem_DO() {
final int QUANTITY = 1;
Product product = new Product("Dummy Product Name",
getUniqueNumber());
Invoice inv = new Invoice( new DummyCustomer() );
LineItem expItem = new LineItem(inv, product, QUANTITY);
// Exercise
inv.addItemQuantity(product, QUANTITY);
// Verify
List lineItems = inv.getLineItems();
assertEquals("number of items", lineItems.size(), 1);
LineItem actual = (LineItem)lineItems.get(0);
assertLineItemsEqual("", expItem, actual);
}
Note that a Dummy Object is not the same as a Null Object [PLOPD3] . A Dummy Object is not used by the SUT, so its behavior is irrelevant. By contrast, a Null Object is used by the SUT but is designed to do nothing. That's a small but very important distinction!
Dummy Objects are in a different league than the other Test Doubles ; they are really an alternative to the attribute value patterns such as Literal Value (page 714 ), Generated Value (page 723 ), and Derived Value (page 718 ). Therefore, we don't need to "configure" them or "install" them. In fact, almost nothing we say about the other Test Doubles applies to Dummy Objects, so we won't mention them again in this chapter.
Test Stubs
A Test Stub is an object that acts as a control point to deliver indirect inputs to the SUT when the Test Stub 's methods are called. Its use allows us to exercise Untested Code paths in the SUT that might otherwise be impossible to traverse during testing. A Responder (see Test Stub ) is a basic Test Stub that is used to inject valid and invalid indirect inputs into the SUT via normal returns from method calls. A Saboteur (see Test Stub ) is a special Test Stub that raises exceptions or errors to inject abnormal indirect inputs into the SUT. Because procedural programming languages do not support objects, they force us to use Procedural Test Stubs (see Test Stub ).
In the following example, the Saboteur— implemented as an anonymous inner class in Java—throws an exception when the SUT calls the getTime method to allow us to verify that the SUT behaves correctly in this case:
public void testDisplayCurrentTime_exception()
throws Exception {
// Fixture setup
// Define and instantiate Test Stub
TimeProvider testStub = new TimeProvider()
{ // Anonymous inner Test Stub
public Calendar getTime() throws TimeProviderEx {
throw new TimeProviderEx("Sample");
}
};
// Instantiate SUT
TimeDisplay sut = new TimeDisplay();
sut.setTimeProvider(testStub);
// Exercise SUT
String result = sut.getCurrentTimeAsHtmlFragment();
// Verify direct output
String expectedTimeString =
"<span class=\"error\">Invalid Time</span>";
assertEquals("Exception", expectedTimeString, result);
}
In procedural programming languages, a Procedural Test Stub is either (1) a Test Stub implemented as a stand-in for an as-yet-unwritten procedure or (2) an alternative implementation of a procedure linked into the program instead of the real implementation of the procedure. Traditionally, Procedural Test Stubs are introduced to allow debugging to proceed while we are waiting for other code to be ready. They are rarely "swapped in" at runtime—this is hard to do in most procedural languages. If we do not mind introducing Test Logic in Production (page 217 ) code, we can implement a Procedural Test Stub using Test Hooks (page 709 ) such as if testing then ... else in the SUT. This is illustrated in the following listing:
public Calendar getTime() throws TimeProviderEx {
Calendar theTime = new GregorianCalendar();
if (TESTING) {
theTime.set(Calendar.HOUR_OF_DAY, 0);
theTime.set(Calendar.MINUTE, 0);}
else {
// just return the calendar
}
return theTime;
};
The key exception occurs in languages that support procedure variables . 1 These variables allow us to implement dynamic binding as long as the client code accesses the procedure to be replaced via a procedure variable.
Test Spies
A Test Spy is an object that can act as an observation point for the indirect outputs of the SUT. To the capabilities of a Test Stub, it adds the ability to quietly record all calls made to its methods by the SUT. The verification part of the test performs Procedural Behavior Verification on those calls by using a series of assertions to compare the actual calls received by the Test Spy with the expected calls.
The following example uses the Retrieval Interface (see Test Spy ) on the Test Spy to verify that the correct information was passed as arguments in the call to the logMessage method by the SUT (the removeFlight method of the facade ).
public void testRemoveFlightLogging_recordingTestStub()
throws Exception {
// Fixture setup
FlightDto expectedFlightDto = createAnUnregFlight();
FlightManagementFacade facade =
new FlightManagementFacadeImpl();
// Test Double setup
AuditLogSpy logSpy = new AuditLogSpy();
facade.setAuditLog(logSpy);
// Exercise
facade.removeFlight(expectedFlightDto.getFlightNumber());
// Verify state
assertFalse("flight still exists after being removed",
facade.flightExists( expectedFlightDto.
getFlightNumber()));
// Verify indirect outputs using retrieval interface of spy
assertEquals("number of calls", 1,
logSpy.getNumberOfCalls());
assertEquals("action code",
Helper.REMOVE_FLIGHT_ACTION_CODE,
logSpy.getActionCode());
assertEquals("date", helper.getTodaysDateWithoutTime(),
logSpy.getDate());
assertEquals("user", Helper.TEST_USER_NAME,
logSpy.getUser());
assertEquals("detail",
expectedFlightDto.getFlightNumber(),
logSpy.getDetail());
}
Mock Objects
A Mock Object is also an object that can act as an observation point for the indirect outputs of the SUT. Like a Test Stub , it may need to return information in response to method calls. Also like a Test Spy , a Mock Object pays attention to how it was called by the SUT. It differs from a Test Spy, however, in that the Mock Object compares actual calls received with the previously defined expectations using assertions and fails the test on behalf of the Test Method . As a consequence, we can reuse the logic employed to verify the indirect outputs of the SUT across all tests that use the same Mock Object . Mock Objects come in two basic flavors:
- A strict Mock Object fails the test if the correct calls are received in a different order than was specified.
- A lenient 2 Mock Object tolerates out-of-order calls. Some lenient Mock Objects tolerate or even ignore unexpected calls or missed calls. That is, the Mock Object may verify only those actual calls that correspond to expected ones.
The following test configures a Mock Object with the arguments of the expected call to logMessage . When the SUT (the removeFlight method) calls logMessage , the Mock Object asserts that each of the actual arguments equals the expected argument. If it discovers that any wrong arguments were passed, the test fails.
public void testRemoveFlight_Mock() throws Exception {
// Fixture setup
FlightDto expectedFlightDto = createAnonRegFlight();
// Mock configuration
ConfigurableMockAuditLog mockLog =
new ConfigurableMockAuditLog();
mockLog.setExpectedLogMessage(
helper.getTodaysDateWithoutTime(),
Helper.TEST_USER_NAME,
Helper.REMOVE_FLIGHT_ACTION_CODE,
expectedFlightDto.getFlightNumber());
mockLog.setExpectedNumberCalls(1);
// Mock installation
FlightManagementFacade facade =
new FlightManagementFacadeImpl();
facade.setAuditLog(mockLog);
// Exercise
facade.removeFlight(expectedFlightDto.getFlightNumber());
// Verify
assertFalse("flight still exists after being removed",
facade.flightExists( expectedFlightDto.
getFlightNumber()));
mockLog.verify();
}
Like Test Stubs, Mock Objects often support configuration with any indirect inputs required to allow the SUT to advance to the point where it would generate the indirect outputs they are verifying.
Fake Objects
A Fake Object is quite different from a Test Stub or a Mock Object in that it is neither directly controlled nor observed by the test. The Fake Object is used to replace the functionality of the real DOC in a test for reasons other than verification of indirect inputs and outputs. Typically, a Fake Object implements the same functionality or a subset of the functionality of the real DOC, albeit in a much simpler way. The most common reasons for using a Fake Object are that the real DOC has not yet been built, is too slow, or is not available in the test environment.
The sidebar " Faster Tests Without Shared Fixtures " (page 319 ) describes how my team encapsulated all database access behind a persistence layer interface and then replaced the persistence layer component with one that used in-memory hash tables instead of a real database, thereby making our tests run 50 times faster. To do so, we used a Fake Database (see Fake Object ) that was something like this one:
public class InMemoryDatabase implements FlightDao{
private List airports = new Vector();
public Airport createAirport(String airportCode,
String name, String nearbyCity)
throws DataException, InvalidArgumentException {
assertParamtersAreValid( airportCode, name, nearbyCity);
assertAirportDoesntExist( airportCode);
Airport result = new Airport(getNextAirportId(),
airportCode, name, createCity(nearbyCity));
airports.add(result);
return result;
}
public Airport getAirportByPrimaryKey(BigDecimal airportId)
throws DataException, InvalidArgumentException {
assertAirportNotNull(airportId);
Airport result = null;
Iterator i = airports.iterator();
while (i.hasNext()) {
Airport airport = (Airport) i.next();
if (airport.getId().equals(airportId)) {
return airport;
}
}
throw new DataException("Airport not found:"+airportId);
}
Providing the Test Double
There are two approaches to providing a Test Double: a Hand-Built Test Double (see Configurable Test Double on page 558 ) , which is coded by the test automater, or a Dynamically Generated Test Double (see Configurable Test Double ) , which is generated at runtime using a framework or toolkit provided by some other developer. 3 All generated Test Doubles must be, by their very nature, Configurable Test Doubles ; these components are covered in more detail in the next section. Hand-Built Test Doubles, by contrast, tend to be Hard-Coded Test Doubles (page 568 ) but can also be made configurable with some additional effort. The following code sample illustrates a hand-coded Inner Test Double (see Hard-Coded Test Double ) that uses Java's anonymous inner class construct:
public void testDisplayCurrentTime_AtMidnight_PS()
throws Exception {
// Fixture setup
// Define and instantiate Test Stub
TimeProvider testStub = new PseudoTimeProvider()
{ // Anonymous inner stub
public Calendar getTime(String timeZone) {
Calendar myTime = new GregorianCalendar();
myTime.set(Calendar.MINUTE, 0);
myTime.set(Calendar.HOUR_OF_DAY, 0);
return myTime;
}
};
// Instantiate SUT
TimeDisplay sut = new TimeDisplay();
// Inject Test Stub into SUT
sut.setTimeProvider(testStub);
// Exercise SUT
String result = sut.getCurrentTimeAsHtmlFragment();
// Verify direct output
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals("Midnight", expectedTimeString, result);
}
We can greatly simplify the development of Hand-Built Test Doubles in statically typed languages such as Java and C# by providing a set of base classes called Pseudo-Objects (see Hard-Coded Test Double ) from which to create subclasses. Pseudo-Objects can reduce the number of methods we need to implement in each Test Stub , Test Spy, or Mock Object to just the ones we expect to be called. They are especially helpful when we are using Inner Test Doubles or Self Shunts (see Hard-Coded Test Double ). The class definition for the Pseudo-Object used in the previous example looks like this:
/**
* Base class for hand-coded Test Stubs and Mock Objects
*/
public class PseudoTimeProvider implements ComplexTimeProvider {
public Calendar getTime() throws TimeProviderEx {
throw new PseudoClassException();
}
public Calendar getTimeDifference(Calendar baseTime,
Calendar otherTime)
throws TimeProviderEx {
throw new PseudoClassException();
}
public Calendar getTime( String timeZone )
throws TimeProviderEx {
throw new PseudoClassException();
}
}
Configuring the Test Double
Some Test Doubles (specifically, Test Stubs and Mock Objects ) need to be told which values to return and/or which values to expect. A Hard-Coded Test Double receives these instructions at design time from the test automater; a Configurable Test Double is told this information at runtime by the test ( Figure 11.9 ). A Test Stub or Test Spy needs to be configured only with the values that will be returned by the methods that the SUT is expected to invoke. A Mock Object also needs to be configured with the names and arguments of all methods we expect the SUT to invoke on it. In all cases, the test automater ultimately decides with which values to configure the Test Double . Not surprisingly, the primary considerations when making this decision are the understandability of the test and the potential reusability of the Test Double code.
Figure 11.9. A Test Double being configured by the test. We can avoid a proliferation of Hard-Coded Test Doubles classes by passing return values or expectation to the Configurable Test Double at runtime.
Fake Objects do not need to be "configured" at runtime because they are just used by the SUT; later outputs depend on the earlier calls by the SUT. Similarly, Dummy Objects do not need to be "configured" because they should never be executed. 4 Procedural Test Stubs are typically built as Hard-Coded Test Doubles . That is, they are hard-coded to return a particular value when the function is called—thus they are the simplest form of Test Double .
A Configurable Test Double can provide either a Configuration Interface (see Configurable Test Double ) or a Configuration Mode (see Configurable Test Double ) that the test can use to configure the Test Double with the values to return or expect. As a consequence, Configurable Test Doubles are reusable across many tests. Use of these Configurable Test Doubles also makes tests more understandable because the values used by the Test Double are visible within the test, thus avoiding the smell of a Mystery Guest (see Obscure Test on page 186 ).
So where should this configuration take place? The installation of the Test Double should be treated just like any other part of fixture setup. Alternatives such as In-line Setup (page 408 ), Implicit Setup (page 424 ), and Delegated Setup (page 411 ) are all available.
Installing the Test Double
Before we exercise the SUT, we need to "install" any Test Doubles on which our test depends. The term "install" here serves as a generic way to describe the process of telling the SUT to use our Test Double, regardless of the exact details regarding how we do it. The normal sequence is to instantiate the Test Double , configure it if it is a Configurable Test Double, and then tell the SUT to use the Test Double either before or as we exercise the SUT. There are several distinct ways to "install" the Test Double, and the choice between them may be as much a matter of style as of necessity if we are designing the SUT for testability. Our choices may be much more constrained, however, when we try to retrofit our tests to an existing design.
The basic choices boil down to Dependency Injection (page 678 ), in which the client software tells the SUT which DOC to use; Dependency Lookup (page 686 ), in which the SUT delegates the construction or retrieval of the DOC to another object; and Test Hook, in which the DOC or the calls to it within the SUT are modified.
If an inversion of control framework is available in our language, our tests can substitute dependencies without much additional work on our part. This removes the need for building in the Dependency Injection or Dependency Lookup mechanism.
Dependency Injection
Dependency Injection is a class of design decoupling in which the client tells the SUT which DOC to use at runtime ( Figure 11.10 ) . The test-driven development (TDD) movement has greatly increased its popularity because Dependency Injection makes for more easily tested designs. This pattern also makes it possible to reuse the SUT more broadly because it removes knowledge of the dependency from the SUT; often the SUT will be aware of only a generic interface that the DOC must implement. Dependency Injection comes in several specific flavors, with the choice between them being largely a matter of taste:
- Setter Injection (see Dependency Injection ) : The SUT accesses the DOC through a public attribute (i.e., a variable or property). The test explicitly sets the attribute after instantiating the SUT to installing the Test Double . The SUT may have previously initialized the attribute with the real DOC in its constructor (in which case the test is replacing it) or the SUT may use Lazy Initialization [SBPP] to initialize the attribute (in which case the SUT will not bother to install the real DOC).
- Constructor Injection (see Dependency Injection ) : The SUT accesses the DOC through a private attribute. The test passes the Test Double to the SUT via a constructor that takes the DOC to be used as an explicit argument and initializes the attribute from it. This may be the primary constructor used by production code clients or it may be an alternative constructor. In the latter case, the primary constructor should call this constructor, passing the default DOC to it as an argument.
- Parameter Injection (see Dependency Injection ) : The SUT receives the DOC as a method parameter. The test passes in a Test Double, whereas the production code passes in the real object. 5 This approach works well when the API of the SUT takes as a parameter the object we need to replace. Although Mock Object aficionados might argue that designing APIs in this way improves the design of the SUT, it is not always possible or practical to pass everything required to each method.
Figure 11.10. A Test Double being "injected" into the SUT by a test. Using Test Doubles requires a means to replace the DOC. Using Dependency Injection involves having the caller supply the dependency to the SUT before or as it is used.
Dependency Lookup
When software is not designed for testability or when Dependency Injection is not appropriate, we may find it convenient to use Dependency Lookup . This pattern also removes the knowledge of exactly which DOC should be used from the SUT, but it does so by having the SUT ask another piece of software to create or find the DOC on its behalf ( Figure 11.11 ) . This opens the door to changing the DOC at runtime without modifying the SUT's code. We do have to modify the behavior of the intermediary somehow, and this is where the specific variants of Dependency Lookup differ from one another:
- Object Factory (see Dependency Lookup ) : The SUT creates the DOC by calling a Factory Method [GOF] on a well-known object instead of using an object constructor to create the DOC directly. The test explicitly tells the Object Factory to create a Test Double instead of a normal DOC whenever this method is called.
- Service Locator (see Dependency Lookup ): The SUT retrieves a previously created service object by asking a well-known Registry [PEAA] object for it. The test configures the Service Locator to return the Test Double when the SUT requests the DOC.
Figure 11.11. A Service Locator being "configured" by a test to return a Test Double to the SUT. Using Test Doubles requires a means to replace the DOC. Using Dependency Lookup involves having the SUT ask a well-known object to provide a reference to the DOC; the test can provide the Service Locator with a Test Double to return.
The line between these two patterns can become quite blurry when we use Lazy Initialization to create the object being returned by a Service Locator . Should it be called an Object Factory instead? Does it really matter which label we apply? Probably not—hence the generic name of Dependency Lookup .
Retrofitting Testability Using a Test-Specific Subclass
Even when none of these mechanisms is built into the SUT, we may be able to retrofit them relatively easily by using a Test-Specific Subclass .
The use of Singletons [GOF] specifically to act as an Object Factory or Service Locator is common. If the Singleton has hard-coded behavior, we may have to turn it into a Substitutable Singleton (see Test-Specific Subclass on page 579 ) to enable overriding the normally returned DOC with our Test Double . The use of Singletons can be avoided through the use of an IOC tool or a manually coded Dependency Injection mechanism. Both of these choices are preferable because they make the test's dependency on a Test Double more obvious. Singletons used for other purposes almost always cause headaches when we are writing tests and should be avoided if possible.
Our test can instantiate a Test-Specific Subclass of the SUT to add a Dependency Injection mechanism or to replace other methods of the SUT with test-specific behavior; see Figure 11.12 . We can override any logic used to access a DOC, thereby making it possible to return a Test Double instead of the normal DOC without modifying the production code. We can also replace the implementations of any methods being called from the method we are testing with Test Stub -like behavior, thereby turning the SUT into its own Subclassed Test Double (see Test-Specific Subclass ). This is one way to inject indirect inputs into the SUT.
Figure 11.12. Using a Test-Specific Subclass of the SUT. When all else fails, we can always try subclassing the SUT to change or expose functionality we need to enable testing
The main prerequisite of using a Test-Specific Subclass of the SUT is that the SUT must use Self-Calls [WWW] to nonprivate methods that implement any functionality we need to override from the test. Small, single-purpose methods rule! The main drawback of this approach is that it is possible to accidentally override parts of the behavior we are intending to test.
We can also subclass the DOC to insert test-specific behavior, effectively turning it into a Subclassed Test Double ( Figure 11.13 ). This strategy is somewhat safer than subclassing the SUT because it avoids the possibility of accidentally overriding those parts of the SUT that we are testing. The trick, however, is to get the SUT to use the Test-Specific Subclass instead of the DOC. In practice, this implies that we must use one of the Dependency Injection or Dependency Lookup techniques, unless the DOC is a Singleton. When the SUT uses a Singleton by calling a static soleInstance method on a hard-coded class name, the test can cause the soleInstance method to return an instance of a Test Double by subclassing the Singleton class and initializing the real Singleton's soleInstance class variable to hold an instance of the Test Double . The returned Test Double may need to be a Subclassed Test Double if the type of the variable used to hold the Singleton's sole instance is hard-coded as the Singleton's class. Although we often use this technique to get a Service Locator to return a different service, but we can also use a Subclassed Test Double directly without an intermediary Service Locator .
Figure 11.13. Using A Test Double subclassed from the DOC. One way to build a Test Double is to subclass the real class and override the implementation of any methods we need to control the indirect inputs or verify indirect outputs.
Other Ways of Retrofitting Testability
All is not lost when none of the techniques described thus far can be used to introduce testability. We still have a few tricks left up our sleeves.
Test Hooks are the "elephant in the room" that no one wants to talk about because they may lead to Test Logic in Production . Test Hooks, however, are a perfectly legitimate way to get legacy code under test when it is too hard or dangerous to introduce one of the techniques described earlier. They are best used as a "transition" strategy to allow Scripted Tests (page 285 ) or Recorded Tests (page 278 ) to be automated to provide a Safety Net (see page 24 ) while large-scale refactoring is undertaken to improve testability. Ideally, once the code has been made more testable, better tests can be prepared using the techniques described earlier and the Test Hooks can be removed.
Michael Feathers [WEwLC] has described several other techniques to replace dependencies with test-specific code under the general heading of finding "object seams." For example, we can replace a depended-on library with a library designed specifically for testing. A seemingly hard-coded dependency can be broken this way. Most of these techniques are less applicable when we need to dynamically replace dependencies within individual tests than either Dependency Injection or Dependency Lookup because they require changes to the environment. Object seams are, however, an excellent way to place legacy code under test so that it can be refactored to introduce either of the previously mentioned dependency-breaking techniques.
We can use aspect-oriented programming (AOP) to install the Test Double behavior by defining a test point-cut that matches the place where the SUT calls the DOC and we would rather have it call the Test Double . Although we need an AOP-enabled development environment to do this, we do not need to deploy the AOP-generated code into a production environment. As a consequence, this technique may be used even in AOP-hostile environments.
Other Uses of Test Doubles
So far, we have covered the testing of indirect inputs and indirect outputs. Now let's look at some other uses of Test Doubles .
Endoscopic Testing
Tim Mackinnon et al. introduced the concept of endoscopic testing [ET] in their initial Mock Objects paper. Endoscopic testing focuses on testing the SUT from the inside by passing in a Mock Object as an argument to the method under test. This allows verification of certain internal behaviors of the SUT that may not always be visible from the outside.
The classic example that Mackinnon and colleagues cite is the use of a mock collection class preloaded with all of the expected members of the collection. When the SUT tries to add an unexpected member, the mock collection's assertion fails. The full stack trace of the internal call stack then becomes visible in the xUnit failure report. If our IDE supports breaking on specified exceptions, we can also inspect the local variables at the point of failure.
Need-Driven Development
A refinement of endoscopic testing is "need-driven development" [MRNO] , in which the dependencies of the SUT are defined as the tests are written. This "outside-in" approach to writing and testing software combines the conceptual elegance of the traditional "top-down" approach to writing code with modern TDD techniques supported by Mock Objects . It allows us to build and test the software layer by layer, starting at the outermost layer before we have implemented the lower layers.
Need-driven development combines the benefits of test-driven development (specifying all software with tests before we build them) with a highly incremental approach to design that removes the need for any speculation about how a depended-on class might be used.
Speeding Up Fixture Setup
Another application of Test Doubles is to reduce the runtime cost of Fresh Fixture (page 311 ) setup. When the SUT needs to interact with other objects that are difficult to create because they have many dependencies, a single Test Double can be created instead of the complex network of objects. When applied to networks of entity objects, this technique is called Entity Chain Snipping (see Test Stub ).
Speeding Up Test Execution
Test Doubles may also be used to speed up tests by replacing slow components with faster ones. Replacing a relational database with an in-memory Fake Object, for example, can reduce test execution times by an order of magnitude! The extra effort required to code the Fake Database is more than offset by the reduced waiting time and the quality improvement due to the more timely feedback that comes from running the tests more frequently. Refer to the sidebar " Faster Tests without Shared Fixtures " on page 319 for a more detailed discussion of this issue.
Other Considerations
Because many of our tests will involve replacing a real DOC with a Test Double , how do we know that the production code will work properly when it uses the real DOC? Of course, we would expect our customer tests to verify behavior with the real DOCs in place (except, possibly, when the real DOCs are interfaces to other systems that need to be stubbed out during single-system testing). We should write a special form of Constructor Test (see Test Method )—a "substitutable initialization test"—to verify that the real DOC is installed properly. The trigger for writing this test is performing the first test that replaces the DOC with a Test Double —that point is often when the Test Double installation mechanism is introduced.
Finally, we want to be careful that we don't fall into the "new hammer trap." 6 Overuse of Test Doubles (and especially Mock Objects or Test Stubs ) can lead to Overspecified Software (see Fragile Test on page 239 ) by encoding implementation-specific information about the design in our tests. The design may be then much more difficult to change if many tests are affected by the change simply because they use a Test Double that has been affected by the design change.
What's Next?
In this chapter, we examined techniques for testing software with indirect inputs and indirect outputs. In particular, we explored the concept of Test Doubles and various techniques for installing them. In Chapter 12 , Organizing Our Tests, we will turn our attention to strategies for organizing the test code into Test Methods and Test Utility Methods (page 599 ) implemented on Testcase Classes (page 373 ) and Test Helpers (page 643 ) .