Design-for-Testability Patterns
Patterns in This Chapter
Dependency Injection 678
Dependency Lookup 686
Humble Object 695
Test Hook 709
Dependency Injection
How do we design the SUT so that we can replace its dependencies at runtime?
The client provides the depended-on object to the SUT.
Almost every piece of code depends on some other classes, objects, modules, or procedures. To unit-test a piece of code properly, we would like to isolate the code from its dependencies. This isolation is difficult to achieve if those dependencies are hard-coded in the form of literal classnames.
Dependency Injection is a way to allow the normal coupling between a SUT and its dependencies to be broken during automated testing.
How It Works
We avoid hard-coding the names of classes on which we depend into our code by providing some other means for the client or system configuration to tell the SUT which objects to use for each dependency as it is executed. As part of the design of the SUT, we arrange to pass the dependency in to the SUT through the "front door." That is, the means to specify the dependency becomes part of the API of the SUT. We can include it as an argument with each method call, include it on the constructor, or make it a settable attribute (property).
When to Use It
We need to provide a means to substitute a depended-on component (DOC) to make it easy to use a Test Double (page 522 ) while testing our code. Static binding —that is, specifying exact types or classes at compile time—severely limits our options regarding how the software is configured as it runs. Dynamic binding creates much more flexible software by deferring the decision of exactly which type or class to use until runtime. Dependency Injection is a good choice for communicating which class to use when we are designing the software from scratch. It offers a natural way to design the code when we are doing test-driven development (TDD) because many of the tests we write for dependent objects seek to replace a DOC with a Test Double .
When we don't have complete control over the code we are testing, such as when we are retrofitting tests to existing code, 1 we may need to use some other means to introduce the Test Doubles . If the SUT uses Dependency Lookup (page 686 ) to find the DOC, we can override the lookup mechanism to return the Test Double . We can also use a Test-Specific Subclass (page 579 ) of the SUT to return a Test Double as long as access to the DOC remains encapsulated behind a method call.
Implementation Notes
Introducing Dependency Injection requires solving two problems. First, we must be able to use a Test Double wherever the real DOC is used. This constraint is primarily an issue in statically typed languages because we must convince the compiler to allow us to pass off a Test Double as the real thing. Second, we must provide a way to tell the SUT to use the Test Double .
Type Compatibility
Whichever way we choose to install the dependency into the SUT, we must also ensure that the Test Double we want to replace it with is "type compatible" with the code that uses the Test Double . This is most easily accomplished if both the real component and the Test Double implement the same interface (in statically typed languages) or have the same signature (in dynamically typed languages). A quick way to introduce a Test Double into existing code is to do an Extract Interface [Fowler] refactoring on the real DOC and then have the Test Double implement the new interface.
Installing the Test Double
There are a number of different ways to tell the SUT to use the Test Double, but they all involve replacing a hard-coded name with a mechanism that determines the type of object to use at execution time. The three basic options are as follows:
- Parameter Injection: We pass the dependency directly to the SUT as we invoke it.
- Constructor Injection: We tell the SUT which DOC to use when we construct it.
- Setter Injection: We tell the SUT about the DOC sometime between when we construct it and when we exercise it.
Each of these three variations of Dependency Injection can be hand-coded. Another option is to use an "Inversion of Control" (IoC) framework to link the various components together at runtime. This scheme avoids superfluous diversity in how Dependency Injection is implemented across the application and can simplify the process of reconfiguring the application for different deployment models.
Variation: Parameter Injection
Parameter Injection is a form of Dependency Injection in which the SUT does not keep or initialize a reference to the DOC; instead, it is passed in as an argument of the method being called on the SUT. All clients of the SUT—whether they are tests or production code—supply the DOC. As a consequence, the SUT is more independent of the context because it makes no assumptions about the dependency other than its usage interface. The main drawback is that Parameter Injection forces the client to know about the dependency, which is more appropriate in some circumstances than in others. Most of the other variants of Dependency Injection move this knowledge somewhere other than the client or at least make it optional.
Parameter Injection is advocated by the original paper on Mock Objects (page 544 ) [ET] . It is especially effective when we are doing true TDD because that's when we have the greatest control over the design. It is possible to introduce Parameter Injection in an optional fashion by providing an alternative signature for the method in question with the extra parameter; we can then have the more traditional style method create the instance of the dependency and call the method that takes the dependency as a parameter.
Variation: Constructor Injection
Both Constructor Injection and Setter Injection involve storing a reference to the DOC as an attribute (field or instance variable) of the SUT. With Dependency Injection, the field is initialized from a constructor argument. The SUT may optionally provide a simpler constructor that calls this constructor with the value normally used in production. When a test wants to replace the real DOC with a Test Double , it passes in the Test Double to the constructor when it builds the SUT.
This approach to introducing Dependency Injection works well when the code includes only one or two constructors and they have small argument lists. Constructor Injection is the only approach that works if the DOC is an active object that creates its own thread of execution during construction; such behavior would make for Hard-to-Test Code (page 209 ), and we should probably consider turning it into a Humble Executable (see Humble Object on page 695 ). If we have a large number of dependencies as constructor arguments, we probably need to refactor the code to remove this code smell.
Variation: Setter Injection
As with Constructor Injection , the SUT holds a reference to the DOC as an attribute (field) that is initialized in the constructor. Where it differs is that the attribute is exposed to the client either as a public attribute or via a "setter" method. When a test wants to replace the real DOC with a Test Double , it assigns to the exposed attribute (or calls the setter with) an instance of the Test Double . This approach works well when constructing the real DOC has no unpleasant side effects and assuming that nothing can happen automatically between the constructor call and the point at which the test calls the setter for the property. Setter Injection cannot be used if the SUT performs any significant processing in the constructor that relies on the dependency. In that case, we must use Constructor Injection . If constructing the real DOC has deleterious side effects, we can avoid creating it via the constructor by modifying the SUT to use Lazy Initialization [SBPP] to instantiate the DOC the first time the SUT needs to use it.
Retrofitting Dependency Injection
When the SUT does not support any of these options "out of the box," we may be able to retrofit this capability via a Test-Specific Subclass . If the actual class to be used is normally retrieved from configuration data, this retrieval should be done by some component other than the SUT and the class then passed to the SUT using Dependency Injection . Such a use of the Humble Object pattern for the client or configuration decouples the SUT from the environment and ensures that tests do not need to set up some external dependency (the configuration file) to introduce the Test Double .
Another possibility is to use aspect-oriented programming (AOP) to insert the Dependency Injection mechanism into the development environment. For example, we might inject the decision to use the Test Double or inject the test-specific logic—the Test Double —directly into the SUT. I don't think we have enough experience with using AOP to call this a pattern just yet.
Motivating Example
The following test cannot be made to pass "as is":
public void testDisplayCurrentTime_AtMidnight() {
// fixture setup
TimeDisplay sut = new TimeDisplay();
// exercise SUT
String result = sut.getCurrentTimeAsHtmlFragment();
// verify direct output
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals( expectedTimeString, result);
}
This test almost always fails because it depends on the current time being returned to the SUT by a DOC. The test cannot control the values being returned by that component, the DefaultTimeProvider . Therefore, this test will pass only when the system time is exactly midnight.
public String getCurrentTimeAsHtmlFragment() {
Calendar currentTime;
try {
currentTime = new DefaultTimeProvider().getTime();
} catch (Exception e) {
return e.getMessage();
}
// etc.
}
Because the SUT is hard-coded to use a particular class to retrieve the time, we cannot replace the DOC with a Test Double . That constraint makes this test nondeterministic and pretty much useless. We need to find a way to gain control over the indirect inputs of the SUT.
Refactoring Notes
We can use a Replace Dependency with Test Double (page 522 ) refactoring to gain control over the time. Setter Injection can be introduced into existing code if we have control over the code and the method in question is not widely used or if we have refactoring tools that support the Introduce Parameter [JBrains] refactoring. Failing that, we can use an Extract Method [Fowler] refactoring to create the new method signature that takes the Dependency Injection as an argument and leave the old method as an Adapter [GOF] that calls the new method.
Example: Parameter Injection
Here's the test rewritten to use Parameter Injection:
public void testDisplayCurrentTime_AtMidnight_PI() {
// Fixture setup
// Test Double instantiation
TimeProvider tpStub = new MidnightTimeProvider();
// Instantiate SUT
TimeDisplay sut = new TimeDisplay();
// Exercise SUT using Test Double
String result = sut.getCurrentTimeAsHtmlFragment(tpStub);
// Verify outcome
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals("Midnight", expectedTimeString, result);
}
In this case, only the test will use the new signature. The existing code can use the old signature and the method adapter instantiates the real dependency object before passing it in.
public String getCurrentTimeAsHtmlFragment(
TimeProvider timeProviderArg) {
Calendar currentTime;
try {
currentTime = timeProviderArg.getTime();
} catch (Exception e) {
return e.getMessage();
}
// etc.
}
Example: Constructor Injection
Here's the same test rewritten to use Constructor Injection :
public void testDisplayCurrentTime_AtMidnight_CI()
throws Exception {
// Fixture setup
// Test Double instantiation
TimeProvider tpStub = new MidnightTimeProvider();
// Instantiate SUT injecting Test Double
TimeDisplay sut = new TimeDisplay(tpStub);
// Exercise SUT
String expectedTimeString =
"<span class=\"tinyBoldText\">12:01 AM</span>";
// Verify outcome
assertEquals("12:01 AM",
expectedTimeString,
sut.getCurrentTimeAsHtmlFragment());
}
To convert the SUT to use Constructor Injection, we can do an Introduce Field [JetBrains] refactoring to hold the DOC in a field that is initialized in the existing constructor. We can then do an Introduce Parameter refactoring to modify all callers of the existing constructor so that they pass the real DOC as a parameter of the constructor. If we cannot or do not want to modify all existing callers of the constructor, we can define a new constructor that takes the DOC as a parameter and modify the existing constructor to instantiate the real DOC and pass it in to our new constructor.
public class TimeDisplay {
private TimeProvider timeProvider;
public TimeDisplay() { // backwards compatible constructor
timeProvider = new DefaultTimeProvider();
}
public TimeDisplay(TimeProvider timeProvider) { // new constructor
this.timeProvider = timeProvider;
}
Another approach is to do an Extract Method refactoring on the call to the constructor and then use Move Method [Fowler] refactoring to move it to an Object Factory (see Dependency Lookup ). That would result in Dependency Lookup .
Example: Setter Injection
Here is the same test refactored to use Setter Injection :
public void testDisplayCurrentTime_AtMidnight_SI()
throws Exception {
// Fixture setup
// Test Double instantiation
TimeProvider tpStub = new MidnightTimeProvider();
// Instantiate SUT
TimeDisplay sut = new TimeDisplay();
// Test Double installation
sut.setTimeProvider(tpStub);
// Exercise SUT
String result = sut.getCurrentTimeAsHtmlFragment();
// Verify outcome
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals("Midnight", expectedTimeString, result);
}
Note the call to setTimeProvider to install the Hard-Coded Test Double (page 568 ). If we had used a Configurable Test Double (page 558 ), its configuration would occur immediately before the call to setTimeProvider .
To refactor the SUT to support Setter Injection, we can do an Introduce Field refactoring to hold the DOC in a variable that is initialized in the existing constructor and call the DOC via this field. We can then expose the field either directly or via a setter so that the test can override its value. Here is the refactored version of the SUT:
public class TimeDisplay {
private TimeProvider timeProvider;
public TimeDisplay() {
timeProvider = new DefaultTimeProvider();
}
public void setTimeProvider(TimeProvider provider) {
this.timeProvider = provider;
}
public String getCurrentTimeAsHtmlFragment()
throws TimeProviderEx {
Calendar currentTime;
try {
currentTime = getTimeProvider().getTime();
} catch (Exception e) {
return e.getMessage();
}
// etc.
Here we chose to use a getter to retrieve the DOC. We could just as easily have used the timeProvider field directly.
Dependency Lookup
How do we design the SUT so that we can replace its dependencies at runtime?
The SUT asks another object to return the depended-on object before it uses it.
Also known as
Service Locator, Object Factory, Component Broker, Component Registry
Almost every piece of code depends on some other classes, objects, modules, or procedures. To unit-test a piece of code properly, we would like to isolate it from its dependencies. Such isolation is difficult to achieve, however, if those dependencies are hard-coded within the code in the form of literal classnames.
Dependency Lookup is a way to allow the normal coupling between a SUT and its dependencies to be broken during automated testing.
How It Works
We avoid hard-coding the names of classes on which the SUT depends into our code because static binding severely limits our options regarding how the software is configured as it runs. Instead, we hard-code that name of a "component broker" that returns a ready-to-use object. The component broker provides some means for the client software or perhaps a system configuration manager to tell the SUT in question which objects to use for each component request.
When to Use It
Dependency Lookup is most appropriate when we need to retrieve DOCs from deep inside the system and it would be too messy to pass the Test Double (page 522 ) in from the client. A good example of such a situation is when we want to replace the data access layer of the system with a Fake Database (see Fake Object on page 551 ) or In-Memory Database (see Fake Object ) to speed up execution of the automated customer tests. It would be too complex for each Subcutaneous Test (see Layer Test on page 337 ) to pass the Fake Database in through the Service Facade [CJ2EEP] and all the way down to the data access layer. Using Dependency Lookup allows the test or even a Setup Decorator (page 447 ) to use a "configuration facade" to install the Fake Database, which the SUT can magically use without any further ado. Jeremy Miller writes:
You cannot understate the value of using a Service Locator for automated testing. We routinely use alternative dependencies in testing, both to deal with difficult dependencies and for test performance. For example, in a functional test we'll collapse a Web site and a backing application server into a single process for better performance.
Dependency Lookup tends to be a lot simpler to retrofit onto existing legacy software because it affects only those places where object construction actually occurs; we do not need to modify every intermediate object or method, as we might have to do with Dependency Injection (page 678 ). It is also much simpler to retrofit existing round-trip tests so that they use a Fake Object to speed them up by wrapping them in a Setup Decorator. With this scheme, we do not have to change each test; instead, we can create new instances of the SUT in each test and still have the test use the same Fake Object because the Service Locator remembers it across tests. 2
The main alternative to Dependency Lookup is to provide a substitution mechanism within the SUT using Dependency Injection . This approach is generally preferable for unit tests because it makes the replacement of the DOC more obvious and directly connected to exercising the SUT. Another option is to use AOP to install test-specific logic using the development tools rather than modifying the design of the software. The least preferred solution is to use a Test Hook (page 709 ) within the SUT to avoid calling the DOC or within the DOC so that it behaves in a test-specific way.
The well-known intermediary may be called a "Service Locator," "Object Factory," "Component Broker," or "Component Registry." While these names imply different semantics (new versus existing objects), this need not be the case. For performance reasons, we may choose to return new objects from a "Service Locator" or "previously enjoyed" objects from an Object Factory . To simplify this discussion, the term "Component Broker" is used here.
Implementation Notes
A desire to use a Test Double when testing our code implies a need to make DOCs substitutable. This constraint rules out hard-coding the names of classes on which we depend into our code because static binding severely limits our options regarding how the software is configured as it runs. One way to avoid this issue is to have the SUT delegate DOC fabrication to another object. Of course, this scheme implies we need a way to get a reference to that object. We solve this recursive problem by having a well-known object act as an intermediary between the test and the DOC. This well-known object is referenced by a hard-coded classname. To be useful for installing Test Doubles, this well-known object must supply a mechanism by which the test can specify the object to be returned.
Dependency Lookup has the following characteristics:
- Either a Singleton [GOF] , a Registry [PEAA] , or some kind of Thread-Specific Storage [POSA2]
- An interface that fully encapsulates which implementation we are using
- A built-in substitution mechanism for replacing the returned object with a Test Double
- Access via well-known global name
The Dependency Lookup mechanism returns an object that can be used directly by the client. The nature of the actual object returned determines whether it is more appropriate to call it a "Service Locator" or an "Object Factory." Once the object is retrieved, the SUT uses it directly. During testing, the test arranges for the Dependency Lookup mechanism to return a test-specific object.
Encapsulated Implementation
A major requirement of Dependency Lookup is the existence of a well-known object to which we can delegate our requests for DOCs. This well-known object could be a Singleton, a Registry, or some kind of Thread-Specific Storage mechanism. 3
The "Component Broker" should encapsulate its implementation from the client (our SUT). That is, the interface provided by the "Component Broker" should not expose whether it is a Singleton or a Registry or whether some type of Thread-Specific Storage mechanism is in use under the covers. In fact, the test environment may want to provide a different implementation specifically to avoid issues caused by Singletons in tests, such as a Substitutable Singleton (see Test-Specific Subclass on page 579 ).
Substitution Mechanism
When a test wants to replace the real DOC with a Test Double , it needs a way to tell the "Component Broker" that a Test Double should be returned instead of the real component. The "Component Broker" may provide a configuration interface to configure it with the object to be returned or the test can replace the component Registry with a suitable Test-Specific Subclass . It may also need to provide a way to restore the original or default configuration of the broker so that the configuration used in one test does not "leak" into another test, effectively changing the "Component Broker" into a Shared Fixture (page 317 ).
A less desirable configuration alternative is to have the "Component Broker" read the classnames to be constructed for each request from a configuration file. This approach poses several problems, however. First, the test must write the file as part of fixture setup unless the test offers a way to replace the file access mechanism. This is sure to result in Slow Tests (page 253 ). Second, this scheme will not work with Configurable Test Doubles (page 558 ) unless the configuration file can also provide initialization data for the object. Finally, the need to write a file opens the door to Interacting Tests (see Erratic Test on page 228 ) because different tests may need different configuration information.
If the "Component Broker" must return objects based on configuration data, a better solution is to have a separate Humble Object (page 695 ) read the file and call a configuration interface on the "Component Broker." The test can then use this same interface to configure the broker on a per-test basis.
Motivating Example
The following test cannot be made to pass "as is":
public void testDisplayCurrentTime_AtMidnight() {
// fixture setup
TimeDisplay sut = new TimeDisplay();
// exercise SUT
String result = sut.getCurrentTimeAsHtmlFragment();
// verify direct output
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals( expectedTimeString, result);
}
This test almost always fails because it assumes that the current time will be returned to the SUT by a DOC. The test cannot control which values are returned by that component (the DefaultTimeProvider ), however, so this test will pass only when the system time is exactly midnight.
public String getCurrentTimeAsHtmlFragment() {
Calendar currentTime;
try {
currentTime = new DefaultTimeProvider().getTime();
} catch (Exception e) {
return e.getMessage();
}
// etc.
}
Because the SUT is hard-coded to use a particular class to retrieve the time, we cannot replace the DOC with a Test Double . That makes this test nondeterministic and pretty much useless. We need to find a way to gain control over the indirect inputs of the SUT.
Refactoring Notes
The first step to making this behavior testable is to replace the hard-coded classname with a call to a "Service Locator":
public String getCurrentTimeAsHtmlFragment() {
Calendar currentTime;
try {
TimeProvider timeProvider =
(TimeProvider) ServiceLocator.getInstance().
findService("Time");
currentTime = timeProvider.getTime();
} catch (Exception e) {
return e.getMessage();
}
// etc.
Although we could have provided a class method to avoid the chained method calls, that step would just move the getInstance into the class method. The next refactoring step depends on whether we have a configuration interface on our "Service Locator." If it makes sense to configure the production version of the "Service Locator," we can introduce the configuration mechanism directly into it (as illustrated in the next example). Otherwise, we can simply override what the Service Locator returns in a Test-Specific Subclass (as illustrated in the second example).
Example: Configurable Registry
This version of the test has been modified to use the configuration interface on the "Service Locator" to install a Test Double:
public void testDisplayCurrentTime_AtMidnight_CSL() {
// Fixture setup
// Test Double configuration
MidnightTimeProvider tpStub = new MidnightTimeProvider();
// Instantiate SUT
TimeDisplay sut = new TimeDisplay();
// Test Double installation
ServiceLocator.getInstance().registerServiceForName(tpStub, "Time");
// Exercise SUT
String result = sut.getCurrentTimeAsHtmlFragment();
// Verify outcome
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals("Midnight", expectedTimeString, result);
}
The code in the SUT was described previously. The code for the Configuration Interface (see Configurable Test Double ) of the Configurable Registry follows:
public class ServiceLocator {
protected ServiceLocator() {};
protected static ServiceLocator soleInstance = null;
public static ServiceLocator getInstance() {
if (soleInstance==null)
soleInstance = new ServiceLocator();
return soleInstance;
}
private HashMap providers = new HashMap();
public ServiceProvider findService(String serviceName) {
return (ServiceProvider) providers.get(serviceName);
}
// configuration interface
public void registerServiceForName( ServiceProvider provider,
String serviceName) {
providers.put( serviceName, provider);
}
}
The interesting thing about this example is our use of a Configuration Interface on a production class rather than a Test Double . In fact, the Configurable Registry avoids the need to use a Test Double by providing the test with a mechanism to alter the service component the Configurable Registry returns.
Example: Substituted Singleton
This version of the test deals with a nonconfigurable Dependency Lookup mechanism by replacing the soleInstance of the "Service Locator" with a Substituted Singleton (see Test-Specific Subclass ). To ensure the reusability of the configuration interface of the Substituted Singleton , we pass the TimeProvider Test Stub (page 529 ) as an argument to overrideSoleInstance .
public void testDisplayCurrentTime_AtMidnight_TSS() {
// Fixture setup
// Test Double configuration
MidnightTimeProvider tpStub = new MidnightTimeProvider();
// Instantiate SUT
TimeDisplay sut = new TimeDisplay();
// Test Double installation
// Replaces the entire Service Locator with one that
// always returns our Test Stub
ServiceLocatorTestSingleton.overrideSoleInstance(tpStub);
// Exercise SUT
String result = sut.getCurrentTimeAsHtmlFragment();
// Verify outcome
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals("Midnight", expectedTimeString, result);
}
Note how the test overrides the object normally returned by getInstance with an instance of a Test-Specific Subclass . The code for the Singleton follows:
public class ServiceLocator {
protected ServiceLocator() {};
protected static ServiceLocator soleInstance = null;
public static ServiceLocator getInstance() {
if (soleInstance==null)
soleInstance = new ServiceLocator();
return soleInstance;
}
private HashMap providers = new HashMap();
public ServiceProvider findService(String serviceName) {
return (ServiceProvider) providers.get(serviceName);
}
}
Note that we had to make the constructor and soleInstance protected rather than private to allow them to be overridden by the subclass. Finally, here is the code for the Substituted Singleton:
public class ServiceLocatorTestSingleton extends ServiceLocator {
private ServiceProvider tpStub;
private ServiceLocatorTestSingleton(TimeProvider newTpStub) {
this.tpStub = newTpStub;
};
// Installation interface
static ServiceLocatorTestSingleton
overrideSoleInstance(TimeProvider tpStub) {
// We could save the real instance before reassigning
// soleInstance so we could restore it later, but we'll
// forego that complexity for this example
soleInstance = new ServiceLocatorTestSingleton( tpStub);
return (ServiceLocatorTestSingleton) soleInstance;
}
// Overridden superclass method
public ServiceProvider findService(String serviceName) {
return tpStub; // Hard-coded; ignores serviceName
}
}
Because it cannot see the private HashMap of providers, this code simply returns the contents of the tpStub field that it initialized in the constructor.
About the Name
Choosing a name for this pattern was tough. Service Locator and Component Broker were already in widespread use. Both are good names for use in their particular circumstance. Unfortunately, neither name can encompass the other, so I had to come up with another name that unified the two major variants. The name Dependency Injection was already in widespread use for the alternate pattern; a desire for consistency with that name led to using Dependency Lookup . See the sidebar " What's in a (Pattern) Name? " on page 576 for more on this decision-making process.
Humble Object
How can we make code testable when it is too closely coupled to its environment?
We extract the logic into a separate, easy-to-test component that is decoupled from its environment.
We are often faced with trying to test software that is closely coupled to some kind of framework. Examples include visual components (e.g., widgets, dialogs) and transactional component plug-ins. Testing these objects is difficult because constructing all the objects with which our SUT needs to interact may be expensive—or even impossible. In other cases, objects may be hard to test because they run asynchronously; examples include active objects (e.g., threads, processes, Web servers) and user interfaces. These objects' asynchronicity introduces uncertainty, a requirement for interprocess coordination, and the need for delays into tests. Faced with these thorny issues, developers often just give up on testing this kind of code. The result: Production Bugs (page 268 ) caused by Untested Code and Untested Requirements .
Humble Object is a way to bring the logic of these hard-to-instantiate objects under test in a cost-effective manner.
How It Works
We extract all the logic from the hard-to-test component into a component that is testable via synchronous tests . This component implements a service interface consisting of methods that expose the logic of the untestable component; the only difference is that these methods are accessible via synchronous method calls. As a result, the Humble Object component becomes a very thin adapter layer that contains very little code. Each time the framework calls the Humble Object , this object delegates its responsibilities to the testable component. If the testable component needs any information from the context, the Humble Object is responsible for retrieving it and passing it to the testable component. The Humble Object code is typically so simple that we often don't bother writing tests for it because it can be quite difficult to set up the environment needed to run those tests.
When to Use It
We can and should introduce a Humble Object whenever we have nontrivial logic in a component that is problematic to instantiate because it depends on a framework or can be accessed only asynchronously. There are lots of reasons for objects being hard to test; consequently, there are lots of variations in how we break the dependencies that are required. The following variations are the most common examples of Humble Object —but we shouldn't be surprised if we sometimes need to invent our own variation.
Variation: Humble Dialog
Graphical user interface (GUI) frameworks require us to provide objects to represent our pages and controls. These objects provide logic to translate user actions into the underlying system actions and to translate the system responses back into user recognizable behavior. This logic may involve invoking the application behind the user interface and/or modifying the state of this or other visual objects.
Visual objects are very difficult to test efficiently because they are tightly coupled to the presentation framework that invokes them. To be effective, a test would need to simulate that environment to provide the visual object with all the information and facilities it requires. Further complicating the issue is the fact that these frameworks often run in their own thread of control, which means that we must use asynchronous tests . These tests are challenging to write, and they often result in Slow Tests (page 253 ) and Nondeterministic Tests (see Erratic Test on page 228 ). Under these circumstances, we may benefit by using a Humble Object to move all of the controller and view-updating logic out of the framework-dependent object and into a testable object.
Variation: Humble Executable
Many programs contain active objects. Active objects have their own thread of execution so they can do things in parallel with other activities of the system. Examples of active objects include anything that runs in a separate process (e.g., Windows applications in .exe files) or thread (in Java, any object that implements Runnable ). These objects may be launched directly by the client, or they may be started automatically, process requests from a queue, and send replies via a return message. Either way, we must write asynchronous tests (complete with interprocess coordination and/or explicit delays and Neverfail Tests; see Production Bugs ) to verify their behavior.
The Humble Executable pattern provides a way to bring the logic of the executable under test without incurring the delays that might otherwise lead to Slow Tests and Nondeterministic Tests . We extract all the logic from the executable into a component that is testable via synchronous tests. This component implements a service interface consisting of methods that expose all logic of the executable; the only difference is that these methods are accessible via synchronous method calls. The testable component may be a Windows DLL, a Java JAR containing a Service Facade [CJ2EEP] class, or some other language component or class that exposes the services of the executable in a testable way.
The Humble Executable component itself contains very little code. All it does in its thread of control is to load the testable component (if a True Humble Object ) and delegate to it. As a result, the Humble Executable requires only one or two tests to verify that it performs this load/delegate function correctly. Although these tests still take seconds to execute, they have a much smaller impact on the overall test suite execution time because so few of them exist. Given that this code will not change very often, these tests can even be omitted from the suite of tests that developers execute before check-in to speed up test suite execution times. Of course, we would still prefer to run the Humble Executable tests as part of the automated build process.
Variation: Humble Transaction Controller
Many applications use databases to persist their state. Fixture setup with databases can be slow and complex, and leftover fixtures can wreak havoc with subsequent tests and test runs. If we are using a Shared Fixture (page 317 ), the fixture's persistence may lead to Erratic Tests . Humble Transaction Controller facilitates testing of the logic that runs within the transaction by making it possible for the test to control the transaction. As a consequence, we can exercise the logic, verify the outcome, and then abort the transaction, leaving no trace of our activity in the database.
To implement Humble Transaction Controller, we use an Extract Method [Fowler] refactoring to move all the logic we want to test out of the code that controls the transaction and into a separate method that knows nothing about transaction control and that can be called by the test. Because the caller controls the transaction, the test can start, commit (if it so chooses), and (most commonly) roll back the transaction. In this case, the behavior—not the dependencies—causes us to bypass the Humble Object when we are testing the business logic. As a result, we are more likely to be able to get away with a Poor Man's Humble Object .
As for the Humble Object , it contains no business logic. Thus the only behavior that needs to be tested is whether the Humble Object commits and rolls back the transaction properly based on the outcome of the methods it calls. We can write a test that replaces the testable component with a Test Stub (page 529 ) that throws an exception and then verify that this activity results in a rollback of the transaction. If we are using a Poor Man's Humble Object , the stub would be implemented as a Subclassed Test Double (see Test-Specific Subclass on page 579 ) that overrides the "real" methods with methods that throw exceptions.
Many of the major application server technologies support this pattern either directly or indirectly by taking transaction control away from the business objects that we write. If we are building our software without using a transaction control framework, we may need to implement our own Humble Transaction Controller . See the " Implementation Notes " section for some ideas on how we can enforce the separation.
Variation: Humble Container Adapter
Speaking of "containers," we often have to implement specific interfaces to allow our objects to run inside an application server (e.g., the "EJB session bean" interface). Another variation on the Humble Object pattern is to design our objects to be container-independent and then have a Humble Container Adapter adapt them to the interface required by container. This strategy makes our logic components easy to test outside the container, which dramatically reduces the time required for an "edit–compile–test" cycle.
Implementation Notes
We can make the logic that normally runs inside the Humble Object testable in several different ways. All of these techniques share one commonality: They involve exposing the logic so that it can be verified using synchronous tests. They vary, however, in terms of how the logic is exposed. Regardless of how logic exposure occurs, test-driven purists would prefer that tests verify that the Humble Object is calling the extracted logic properly. This can be done by replacing the real logic methods with some kind of Test Double (page 522 ) implementation.
Variation: Poor Man's Humble Object
The simplest way to isolate and expose each piece of logic we want to verify is to place it into a separate method. We can do so by using an Extract Method refactoring on in-line logic and then making the resulting method visible from the test. Of course, this method cannot require anything from the context. Ideally everything the method needs to do its work will be passed in as arguments but this information could also be placed in fields. Problems may arise if the testable component needs to call methods to access information it needs and those methods are dependent on the (nonexistent/faked) context, as this dependency makes writing the tests more complex.
This approach, which constitutes the "poor man's" Humble Object, works well if no obstacles prevent the instantiation of the Humble Object (e.g., automatically starting its thread, no public constructor, unsatisfiable dependencies). Use of a Test-Specific Subclass can also help break these dependencies by providing a test-friendly constructor and exposing private methods to the test.
When testing a Subclassed Humble Object or a Poor Man's Humble Object , we can build the Test Spy (page 538 ) as a Subclassed Test Double of the Humble Object to record when the methods in question were called. We can then use assertions within the Test Method (page 348 ) to verify that the values recorded match the values expected.
Variation: True Humble Object
At the other extreme, we can put the logic we want to test into a separate class and have the Humble Object delegate to an instance of it. This approach, which was implied in the introduction to this pattern, will work in almost any circumstance where we have complete control over the code.
Sometimes the host framework requires that its objects hold certain responsibilities that we cannot move elsewhere. For example, a GUI framework expects its view objects to contain data for the controls of the GUI and the data that those controls display on the screen. In these cases we must either give the testable object a reference to the Humble Object and have it manipulate the data for that object or put some minimal update logic in the Humble Object and accept that it won't be covered by automated tests. The former approach is almost always possible and is always preferable.
To refactor to a True Humble Object , we normally do a series of Extract Method refactorings to decouple the public interface of the Humble Object from the implementation logic we plan to delegate. Then we do an Extract Class [Fowler] refactoring to move all the methods—except the ones that define the public interface of the Humble Object —to the new "testable" class. We introduce an attribute (a field) to hold a reference to an instance of the new class and initialize it to an instance of the new class either as part of the constructor or using Lazy Initialization [SBPP] in each interface method.
When testing a True Humble Object (where the Humble Object delegates to a separate class), we typically use a Lazy Mock Object (see Mock Object on page 544 ) or Test Spy to verify that the extracted class is called correctly. By contrast, using the more common Active Mock Object (see Mock Object ) is problematic in this situation because the assertions are made on a different thread from the Testcase Object (page 382 ) and failures won't be detected unless we find a way to channel them back to the test thread.
To ensure that the extracted testable component is instantiated properly, we can use an observable Object Factory (see Dependency Lookup on page 686 ) to construct the extracted component. The test can register as a listener to verify the correct method is called on the factory. We can also use a regular factory object and replace it during the test with a Mock Object or Test Stub to monitor which factory method was called.
Variation: Subclassed Humble Object
In between the extremes of the Poor Man's Humble Object and the True Humble Object are approaches that involve clever use of subclassing to put the logic into separate classes while still allowing them to be on a single object. A number of different ways to do this are possible, depending on whether the Humble Object class needs to subclass a specific framework class. I won't go into a lot of detail here as this technique is very specific to the language and runtime environment. Nevertheless, you should recognize that the basic options are either having the framework-dependent class inherit the logic to be tested from a superclass or having the class delegate to an abstract method that is implemented by a subclass.
Motivating Example (Humble Executable)
In this example, we are testing some logic that runs in its own thread and processes each request as it arrives. In each test, we start up the thread, send it some messages, and wait long enough so that our assertions pass. Unfortunately, it takes several seconds for the thread to start up, become initialized, and process the first request. Thus the test fails sporadically unless we include a two-second delay after starting the thread.
public class RequestHandlerThreadTest extends TestCase {
private static final int TWO_SECONDS = 3000;
public void testWasInitialized_Async()
throws InterruptedException {
// Setup
RequestHandlerThread sut = new RequestHandlerThread();
// Exercise
sut.start();
// Verify
Thread.sleep(TWO_SECONDS);
assertTrue(sut.initializedSuccessfully());
}
public void testHandleOneRequest_Async()
throws InterruptedException {
// Setup
RequestHandlerThread sut = new RequestHandlerThread();
sut.start();
// Exercise
enqueRequest(makeSimpleRequest());
// Verify
Thread.sleep(TWO_SECONDS);
assertEquals(1, sut.getNumberOfRequestsCompleted());
assertResponseEquals(makeSimpleResponse(), getResponse());
}
}
Ideally, we would like to test the thread with each kind of transaction individually to achieve better Defect Localization (see page 22 ). Unfortunately, if we did so our test suite would take many minutes to run because each test includes a delay of several seconds. Another problem is that the tests won't result in an error if our active object has an exception in its own thread.
A two-second delay may not seem like a big deal, but consider what happens when we have a dozen such tests. It would take us almost half a minute to run these tests. Contrast this performance with that of normal tests—we can run several hundred of those tests each second. Testing via the executable is affecting our productivity negatively. For the record, here's the code for the executable:
public class RequestHandlerThread extends Thread {
private boolean _initializationCompleted = false;
private int _numberOfRequests = 0;
public void run() {
initializeThread();
processRequestsForever();
}
public boolean initializedSuccessfully() {
return _initializationCompleted;
}
void processRequestsForever() {
Request request = nextMessage();
do {
Response response = processOneRequest(request);
if (response != null) {
putMsgOntoOutputQueue(response);
}
request = nextMessage();
} while (request != null);
}
}
To avoid the distraction of the business logic, I have already used an Extract Method refactoring to move the real logic into the method processOneRequest . Likewise, the actual initialization logic is not shown here; suffice it to say that this logic sets the variable _initializationCompleted when it finishes successfully.
Refactoring Notes
To create a Poor Man's Humble Object , we expose the methods to make them visible from the test. (If the code used in-line logic, we would do an Extract Method refactoring first.) If there were any dependencies on the context, we would need to do an Introduce Parameter [JBrains] refactoring or an Introduce Field [JetBrains] refactoring so that the processOneRequest method need not access anything from the context.
To create a true Humble Object , we can do an Extract Class refactoring on the executable to create the testable component, leaving behind just the Humble Object as an empty shell. This step typically involves doing the Extract Method refactoring described above to separate the logic we want to test (e.g., the initializeThread method and the processOneRequest method) from the logic that interacts with the context of the executable. We then do an Extract Class refactoring to introduce the testable component class (essentially a single Strategy [GOF] object) and move all methods except the public interface methods over to it. The Extract Class refactoring includes introducing a field to hold a reference to the new object and creating an instance. It also includes fixing all of the public methods so that they call the methods that were moved to the new testable class.
Example: Poor Man's Humble Executable
Here is the same set of tests rewritten as a Poor Man's Humble Object:
public void testWasInitialized_Sync()
throws InterruptedException {
// Setup
RequestHandlerThread sut = new RequestHandlerThread();
// Exercise
sut.initializeThread();
// Verify
assertTrue(sut.initializedSuccessfully());
}
public void testHandleOneRequest_Sync()
throws InterruptedException {
// Setup
RequestHandlerThread sut = new RequestHandlerThread();
// Exercise
Response response = sut.processOneRequest(makeSimpleRequest());
// Verify
assertEquals(1, sut.getNumberOfRequestsCompleted());
assertResponseEquals(makeSimpleResponse(), response);
}
Here, we have made the methods initializeThread and processOneRequest public so that we can call them synchronously from the test. Note the absence of a delay in this test. This approach works well as long as we can instantiate the executable component easily.
Example: True Humble Executable
Here is the code for our SUT refactored to use a True Humble Executable :
public class HumbleRequestHandlerThread extends Thread
implements Runnable {
public RequestHandler requestHandler;
public HumbleRequestHandlerThread() {
super();
requestHandler = new RequestHandlerImpl();
}
public void run() {
requestHandler.initializeThread();
processRequestsForever();
}
public boolean initializedSuccessfully() {
return requestHandler.initializedSuccessfully();
}
public void processRequestsForever() {
Request request = nextMessage();
do {
Response response = requestHandler.processOneRequest(request);
if (response != null) {
putMsgOntoOutputQueue(response);
}
request = nextMessage();
} while (request != null);
}
Here, we have moved the method processOneRequest to a separate class that we can instantiate easily. Below is the same test rewritten to take advantage of the extracted component. Note the absence of a delay in this test.
public void testNotInitialized_Sync()
throws InterruptedException {
// Setup/Exercise
RequestHandler sut = new RequestHandlerImpl();
// Verify
assertFalse("init", sut.initializedSuccessfully());
}
public void testWasInitialized_Sync()
throws InterruptedException {
// Setup
RequestHandler sut = new RequestHandlerImpl();
// Exercise
sut.initializeThread();
// Verify
assertTrue("init", sut.initializedSuccessfully());
}
public void testHandleOneRequest_Sync()
throws InterruptedException {
// Setup
RequestHandler sut = new RequestHandlerImpl();
// Exercise
Response response = sut.processOneRequest( makeSimpleRequest() );
// Verify
assertEquals( 1, sut.getNumberOfRequestsDone());
assertResponseEquals( makeSimpleResponse(), response);
}
Because we have introduced delegation to another object, we should probably verify that the delegation occurs properly. The next test verifies that the Humble Object calls the initializeThread method and the processOneRequest method on the newly created testable component:
public void testLogicCalled_Sync()
throws InterruptedException {
// Setup
RequestHandlerRecordingStub mockHandler =
new RequestHandlerRecordingStub();
HumbleRequestHandlerThread sut = new HumbleRequestHandlerThread();
// Mock Installation
sut.setHandler( mockHandler );
sut.start();
// Exercise
enqueRequest(makeSimpleRequest());
// Verify
Thread.sleep(TWO_SECONDS);
assertTrue("init", mockHandler.initializedSuccessfully() );
assertEquals( 1, mockHandler.getNumberOfRequestsDone() );
}
Note that this test does require at least a small delay to allow the thread to start up. The delay is shorter, however, because we have replaced the real logic component with a Test Double that responds instantly and only one test now requires the delay. We could even move this test to a separate test suite that is run less frequently (e.g., only during the automated build process) to ensure that all tests performed before each check-in run quickly.
The other significant thing to note is that we are using a Test Spy rather than a Mock Object . Because the assertions done by the Mock Object would be raised in a different thread from the Test Method, the Test Automation Framework (page 298 )—in this example, JUnit—won't catch them. As a consequence, the test might indicate "pass" even though assertions in the Mock Object are failing. By making the assertions in the Test Method , we avoid having to do something special to relay the exceptions thrown by the Mock Object back to the thread in which the Test Method is executing.
The preceding test verified that our Humble Object actually delegates to the Test Spy that we have installed. It would also be a good idea to verify that our Humble Object actually initializes the variable holding the delegate to the appropriate class. Here's a simple way to do so:
public void testConstructor() {
// Exercise
HumbleRequestHandlerThread sut = new HumbleRequestHandlerThread();
// Verify
String actualDelegateClass = sut.requestHandler.getClass().getName();
assertEquals( RequestHandlerImpl.class.getName(),
actualDelegateClass);
}
This Constructor Test (see Test Method ) verifies that a specific attribute has been initialized.
Example: Humble Dialog
Many development environments let us build the user interface visually by dragging and dropping various objects ("widgets") onto a canvas. They let us add behavior to these visual objects by selecting one of several possible actions or events specific to that visual object and typing logic into the code window presented by the IDE. This logic may involve invoking the application behind the user interface or it may involve modifying the state of this or some other visual object.
Visual objects are very difficult to test efficiently because they are tightly coupled to the presentation framework that invokes them. To provide the visual object with all the information and facilities it requires, the test would need to simulate that environment—quite a challenge. This makes testing very complicated, so much so that many development teams don't bother testing the presentation logic at all. This lack of testing, not surprisingly, often leads to Production Bugs caused by untested code and Untested Requirements .
To create the Humble Dialog , we extract all the logic from the view component into a nonvisual component that is testable via synchronous tests. If this component needs to update the view object's ( Humble Dialog's ) state, the Humble Dialog is passed in as an argument. When testing the nonvisual component, we typically replace the Humble Dialog with a Mock Object that is configured with the indirect input values and the expected behavior (indirect outputs). In GUI frameworks that require the Humble Dialog to register itself with the framework for each event it wishes to see, the nonvisual component can register itself instead of the Humble Dialog (as long as that doesn't introduce unmanageable dependencies on the context). This flexibility makes the Humble Dialog even simpler because the events go directly to the nonvisual component and require no delegation logic.
The following code sample is taken from a VB view component ( .ctl ) that includes some nontrivial logic. It is part of a custom plug-in we built for Mercury Interactive's TestDirector tool.
' Interface method, TestDirector will call this method
' to display the results.
Public Sub ShowResultEx(TestSetKey As TdTestSetKey, _
TSTestKey As TdTestKey, _
ResultKey As TdResultKey)
Dim RpbFiles As OcsRpbFiles
Set RpbFiles = getTestResultFileNames(ResultKey)
ResultsFileName = RpbFiles.ActualResultFileName
ShowFileInBrowser ResultsFileName
End Sub
Function getTestResultFileNames(ResultKey As Variant) As OcsRpbFiles
On Error GoTo Error
Dim Attachments As Collection
Dim thisTest As Run
Dim RpbFiles As New OcsRpbFiles
Call EnsureConnectedToTd
Set Attachments = testManager.GetAllAttachmentsOfRunTest(ResultKey)
Call RpbFiles.LoadFromCollection(Attachments, "RunTest")
Set getTestResultFileNames = RpbFiles
Exit Function
Error:
' do something ...
End Function
Ideally, we would like to test the logic. Unfortunately, we cannot construct the objects passed in as parameters because they don't have public constructors. Passing in objects of some other type isn't possible either, because the types of the function parameters are hard-coded to be specific concrete classes.
We can do an Extract Testable Component (page 735 ) refactoring on the executable to create the testable component, leaving behind just the Humble Dialog as an empty shell. This approach typically involves doing several Extract Method refactorings (already done in the original example to make the refactoring easier to understand), one for each chunk of logic that we want to move. We then do an Extract Class refactoring to create our new testable component class. The Extract Class refactoring may include both Move Method [Fowler] and Move Field [Fowler] refactorings to move the logic and the data it requires out of the Humble Dialog and into the new testable component.
Here's the same view converted to a Humble Dialog :
' Interface method, TestDirector will call this method
' to display the results.
Public Sub ShowResultEx(TestSetKey As TdTestSetKey, _
TSTestKey As TdTestKey, _
ResultKey As TdResultKey)
Dim RpbFiles As OcsRpbFiles
Call EnsureImplExists
Set RpbFiles = Implementation.getTestResultFileNames(ResultKey)
ResultsFileName = RpbFiles.ActualResultFileName
ShowFileInBrowser ResultsFileName
End Sub
Private Sub EnsureImplExists()
If Implementation Is Nothing Then
Set Implementation = New OcsScriptViewerImpl
End If
End Sub
Here's the testable component OcsScriptViewerImpl that the Humble Object calls:
' ResultViewer Implementation:
Public Function getTestResultFileNames(ResultKey As Variant) As OcsRpbFiles
On Error GoTo Error
Dim Attachments As Collection
Dim thisTest As Run
Dim RpbFiles As New OcsRpbFiles
Call EnsureConnectedToTd
Set Attachments = testManager.GetAllAttachmentsOfRunTest(ResultKey)
Call RpbFiles.LoadFromCollection(Attachments, "RunTest")
Set getTestResultFileNames = RpbFiles
Exit Function
Error:
' do something ...
End Function
We could now instantiate this OcsScriptViewerImpl class easily and write VbUnit tests for it. I've omitted the tests for space reasons because they don't really show anything particularly interesting.
Example: Humble Transaction Controller
Transaction Rollback Teardown (page 668 ) contains an example of writing tests that bypass the Humble Transaction Controller.
Further Reading
See http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf for Michael Feathers' original write-up of the Humble Dialog pattern.
Test Hook
How do we design the SUT so that we can replace its dependencies at runtime?
We modify the SUT to behave differently during the test.
Almost every piece of code depends on some other classes, objects, modules, or procedures. To unit-test a piece of code properly, we would like to isolate it from its dependencies. Such isolation is difficult to achieve if those dependencies are hard-coded within the code in the form of literal classnames.
Test Hook is a "method of last resort" for introducing test-specific behavior during automated testing.
How It Works
We modify the behavior of the SUT to support testing by putting a hook directly into the SUT or into a DOC. This approach implies that we use some kind of testing flag that can be checked in the appropriate place.
When to Use It
Sometimes it is appropriate to use this "pattern of last resort" when we cannot use either Dependency Injection (page 678 ) or Dependency Lookup (page 686 ). In this situation, we use a Test Hook because we have no other way to address the Untested Code (see Production Bugs on page 268 ) caused by a Hard-Coded Dependency (see Hard-to-Test Code on page 209 ).
A Test Hook may be the only way to introduce Test Double (page 522 ) behavior when we are programming in a procedural language that does not support objects, function pointers, or any other form of dynamic binding.
Test Hooks can be used as a transition strategy to bring legacy code under the testing umbrella. We can introduce testability using the Test Hooks and then use those Tests as Safety Net (see page 24 ) while we refactor for even more testability. At some point we should be able to discard the initial round of tests that required the Test Hooks because we have enough "modern" tests to protect us.
Implementation Notes
The essence of the Test Hook pattern is that we insert some code into the SUT that lets us test it. Regardless of how we insert this code into the SUT, the code itself can either
- Divert control to a Test Double instead of the real object, or
- Be the Test Double within the real object, or
- Be a test-specific Decorator [GOF] that delegates to the real object when in production.
The flag that indicates testing is in progress can be a compile-time constant, which may, for example, cause the compiler to optimize out all the testing logic. In languages that support preprocessors or compiler macros, such constructs may also be used to remove the Test Hook before the code enters the production phase. The value of the flag can also be read in from configuration data or stored in a global variable that the test sets directly.
Motivating Example
The following test cannot be made to pass "as is":
public void testDisplayCurrentTime_AtMidnight() {
// fixture setup
TimeDisplay sut = new TimeDisplay();
// exercise SUT
String result = sut.getCurrentTimeAsHtmlFragment();
// verify direct output
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals( expectedTimeString, result);
}
This test almost always fails because it depends on a DOC to return the current time to the SUT. The test cannot control the values returned by that component, the DefaultTimeProvider . As a consequence, this test will pass only when the system time is exactly midnight.
public String getCurrentTimeAsHtmlFragment() {
Calendar currentTime;
try {
currentTime = new DefaultTimeProvider().getTime();
} catch (Exception e) {
return e.getMessage();
}
// etc.
}
Because the SUT is hard-coded to use a particular class to retrieve the time, we cannot replace the DOC with a Test Double . As a result, this test is nondeterministic and pretty much useless. We need to find a way to gain control over the indirect inputs of the SUT.
Refactoring Notes
We can introduce a Test Hook by creating a flag that can be checked into the SUT. We then wrap the production code with an if/then/else control structure and put the test-specific logic into the then clause.
Example: Test Hook in System Under Test
Here's the production code modified to accommodate testing via a Test Hook:
public String getCurrentTimeAsHtmlFragment() {
Calendar theTime;
try {
if (TESTING) {
theTime = new GregorianCalendar();
theTime.set(Calendar.HOUR_OF_DAY, 0);
theTime.set(Calendar.MINUTE, 0);}
else {
theTime = new DefaultTimeProvider().getTime();
}
} catch (Exception e) {
return e.getMessage();
}
// etc.
Here we have implemented the testing flag as global constant, which we can edit as necessary. This flexibility implies a separate build step is necessary for versions of the system to be tested. Such a strategy is somewhat safer than using a dynamic configuration parameter or member variable because many compilers will optimize this hook right out of the object code.
Example: Test Hook in Depended-on Component
We can also introduce a Test Hook by putting the hook into a DOC rather than into the SUT:
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;
};
This approach is somewhat better because we are not modifying the SUT as we test it.