Test Automation Strategy
About This Chapter
In previous chapters, we saw some of the problems we might encounter with test automation. In Chapter 5 , Principles of Test Automation, we learned about some of the principles we can apply to help address those problems. This chapter gets a bit more concrete but still focuses at the 30,000-foot level. In the logical sequence of things, test strategy comes before fixture setup but is a somewhat more advanced topic. If you are new to test automation using xUnit, you may want to skip this chapter and come back after reading more about the basics of xUnit in Chapter 7 , xUnit Basics, and about fixture setup and teardown in Chapter 8 , Transient Fixture Management, and subsequent chapters.
What's Strategic?
As the story in the preface amply demonstrates, it is easy to get off on the wrong foot. This is especially true when you lack experience in test automation and when this testing strategy is adopted "bottom up." If we catch the problems early enough, the cost of refactoring the tests to eliminate the problems can be manageable. If, however, the problems are left to fester for too long or the wrong approach is taken to address them, a very large amount of effort can be wasted. This is not to suggest that we should follow a "big design upfront" (BDUF) approach to test automation. BDUF is almost always the wrong answer. Rather, it is helpful to be aware of the strategic decisions necessary and to make them "just in time" rather than "much too late." This chapter gives a "head's up" about some of the strategic issues we want to keep in mind so that we don't get blindsided by them later.
What makes a decision "strategic"? A decision is strategic if it is "hard to change." That is, a strategic decision affects a large number of tests, especially such that many or all the tests would need to be converted to a different approach at the same time. Put another way, any decision that could cost a large amount of effort to change is strategic.
Common strategic decisions include the following considerations:
- Which kinds of tests to automate?
- Which tools to use to automate them?
- How to manage the test fixture?
- How to ensure that the system is easily tested and how the tests interact with the SUT?
Each of these decisions can have far-reaching consequences, so they are best made consciously, at the right time, and based on the best available information.
The strategies and more detailed patterns described in this book are equally applicable regardless of the kind of Test Automation Framework (page 298 ) we choose to use. Most of my experience is with xUnit, so it is the focus of this book. But "don't throw out the baby with the bath water": If you find yourself using a different kind of Test Automation Framework, remember that most of what you learn in regard to xUnit may still be applicable.
Which Kinds of Tests Should We Automate?
Roughly speaking, we can divide tests into the following two categories:
- Per-functionality tests (also known as functional tests) verify the behavior of the SUT in response to a particular stimulus.
- Cross-functional tests verify various aspects of the system's behavior that cut across specific functionality.
Figure 6.1 shows these two basic kinds of tests as two columns, each of which is further subdivided into more specific kinds of tests.
Figure 6.1. A summary of the kinds of tests we write and why. The left column contains the tests we write that describe the functionality of the product at various levels of granularity; we perform these tests to support development. The right column contains tests that span specific chunks of functionality; we execute these tests to critique the product. The bottom of each cell describes what we are trying to communicate or verify.
Per-Functionality Tests
Per-functionality tests verify the directly observable behavior of a piece of software. The functionality can be business related (e.g., the principal use cases of the system) or related to operational requirements (e.g., system maintenance and specific fault-tolerance scenarios). Most of these requirements can also be expressed as use cases, features, user stories, or test scenarios.
Per-functionality tests can be characterized by whether the functionality is business (or user) facing and by the size of the SUT on which they operate.
Customer Tests
Customer tests verify the behavior of the entire system or application. They typically correspond to scenarios of one or more use cases, features, or user stories. These tests often go by other names such as functional tests, acceptance tests, or end-user tests. Although they may be automated by developers, their key characteristic is that an end user should be able to recognize the behavior specified by the test even if the user cannot read the test representation.
Unit Tests
Unit tests verify the behavior of a single class or method that is a consequence of a design decision. This behavior is typically not directly related to the requirements except when a key chunk of business logic is encapsulated within the class or method in question. These tests are written by developers for their own use; they help developers describe what "done looks like" by summarizing the behavior of the unit in the form of tests.
Component Tests
Component tests verify components consisting of groups of classes that collectively provide some service. They fit somewhere between unit tests and customer tests in terms of the size of the SUT being verified. Although some people call these "integration tests" or "subsystem tests," those terms can mean something entirely different from "tests of a specific larger-grained subcomponent of the overall system."
Fault Insertion Tests
Fault insertion tests typically show up at all three levels of granularity within these functional tests, with different kinds of faults being inserted at each level. From a test automation strategy point of view, fault insertion is just another set of tests at the unit and component test levels. Things get more interesting at the whole-application level, however. Inserting faults here can be hard to automate because it is challenging to automate insertion of the faults without replacing parts of the application.
Cross-Functional Tests
Property Tests
Performance tests verify various "nonfunctional" (also known as "extra-functional" or "cross-functional") requirements of the system. These requirements are different in that they span the various kinds of functionality. They often correspond to the architectural "-ilities." These kinds of tests include
- Response time tests
- Capacity tests
- Stress tests
From a test automation perspective, many of these tests must be automated (at least partially) because human testers would have a hard time creating enough load to verify the behavior under stress. While we can run the same test many times in a row in xUnit, the xUnit framework is not particularly well suited to automating performance tests.
One advantage of agile methods is that we can start running these kinds of tests quite early in the project—as soon as the key components of the architecture have been roughed in and the skeleton of the functionality is executable. The same tests can then be run continuously throughout the project as new features are added to the system skeleton.
Usability Tests
Usability tests verify "fitness for purpose" by confirming that real users can use the software application to achieve the stated goals. These tests are very difficult to automate because they require subjective assessment by people regarding how easy it is to use the SUT. For this reason, usability tests are rarely automated and will not be discussed further in this book.
Exploratory Testing
Exploratory testing is a way to determine whether the product is self-consistent. The testers use the product, observe how it behaves, form hypotheses, design tests to verify those hypotheses, and exercise the product with them. By its very nature, exploratory testing cannot be automated, although automated tests can be used to set up the SUT in preparation for doing exploratory testing.
Which Tools Do We Use to Automate Which Tests?
Choosing the right tool for the job is as important as having good skills with the tools selected for use. A wide array of tools are available in the marketplace, and it is easy to be seduced by the features of a particular tool. The choice of tool is a strategic decision: Once we have invested a lot of time and effort in learning a tool and automating many tests using that tool, it becomes much more difficult to change to a different tool.
There are two fundamentally different approaches to automating tests ( Figure 6.2 ). The Recorded Test (page 278 ) approach involves the use of tools that monitor our interactions with the SUT while we test it manually. This information is then saved to a file or database and becomes the script for replaying this test against another (or even the same) version of the SUT. The main problem with Recorded Tests is the level of granularity they record. Most commercial tools record actions at the user interface (UI) element level, which results in Fragile Tests (page 239 ).
Figure 6.2. A summary of the three dimensions of test automation choices. The left side shows the two ways of interacting with the SUT. The bottom edge enumerates how we create the test scripts. The front-to-back dimension categorizes the different sizes of SUT we may choose to test.
The second approach to automating tests, Hand-Scripted Tests (see Scripted Test on page 285 ) involves the hand-coding of test programs ("scripts") that exercise the system. While xUnit is probably the most commonly used Test Automation Framework for preparing Hand-Scripted Tests , they may be prepared in other ways, including "batch" files, macro languages, and commercial or open-source test tools. Some of the better-known open-source tools for preparing Scripted Tests are Watir (test scripts coded in Ruby and run inside Internet Explorer), Canoo WebTest (tests scripted in XML and run using the WebTest tool), and the ever-popular Fit (and its wiki-based sibling FitNesse ). Some of these tools even provide a test capture capability, thereby blurring the lines between Scripted Tests and Recorded Tests .
Choosing which test automation tools to use is a large part of the test strategy decision. A full survey of the different kinds of tools available is beyond the scope of this book, but a somewhat more detailed treatment of the topic is available in [ARTRP] . The following sections summarize the information here to provide an overview of the strengths and weaknesses of each approach.
Test Automation Ways and Means
Figure 6.3 depicts the decision-making possibilities as a matrix. In theory, there are 2 × 2 × 3 possible combinations in this matrix, but it is possible to understand the primary differences between the approaches by looking at the front face of the cube. Some of the four quadrants are applicable to all levels of granularity; others are primarily used for automating customer tests.
Figure 6.3. The choices on the front face of the cube. A more detailed look at the front face of the cube in Figure 6.2 along with the advantages (+) and disadvantages of each (−).
Upper-Right Quadrant: Modern xUnit
The upper-right quadrant of the front face of the cube is dominated by the xUnit family of testing frameworks. These frameworks involve hand-scripting tests that exercise the system at all three levels of granularity (system, component, and unit) via internal interfaces. A good example is unit tests automated using JUnit or NUnit.
Lower-Right Quadrant: Scripted UI Tests
This quadrant represents a variation on the "modern xUnit" approach, with the most common examples being the use of HttpUnit, JFCUnit , Watir, or similar tools to hand-script tests using the UI. It is also possible to hand-script tests using commercial Recorded Test tools such as QTP . These approaches all reside within the lower-right quadrant at various levels of SUT granularity. For example, when used for customer tests, these tools would perform at the system test level of granularity. They could also be used to test just the UI component of the system (or possibly even some UI units such as custom widgets), although this effort would require stubbing out the actual system behind the UI.
Lower-Left Quadrant: Robot User
The "robot user" quadrant focuses on recording tests that interact with the system via the UI. Most commercial test automation tools follow this approach. It applies primarily at the "whole system" granularity but, like scripted UI Tests, could be applied to the UI components or units if the rest of the system can be stubbed out.
Upper-Left Quadrant: Internal Recording
For completeness, the upper-left quadrant involves creating Recorded Tests via an API somewhere behind the UI by recording all inputs and responses as the SUT is exercised. It may even involve inserting observation points between the SUT (at whatever granularity we are testing) and any DOCs. During test playback, the test APIs inject the inputs recorded earlier and compare the results with what was recorded
This quadrant is not well populated with commercial tools 1 but is a feasible option when building a Recorded Test mechanism into the application itself.
Introducing xUnit
The xUnit family of Test Automation Frameworks is designed for use in automating programmer tests. Its design is intended to meet the following goals:
- Make it easy for developers to write tests without needing to learn a new programming language. xUnit is available in most languages in use today.
- Make it easy to test individual classes and objects without needing to have the rest of the application available. xUnit is designed to allow us to test the software from the inside; we just have to design for testability to take advantage of this capability.
- Make it easy to run one test or many tests with a single action. xUnit includes the concept of a test suite and Suite of Suites (see Test Suite Object on page 387 ) to support this kind of test execution.
- Minimize the cost of running the tests so programmers aren't discouraged from running the existing tests. For this reason, each test should be a Self-Checking Test (page 26 ) that implements the Hollywood principle . 2
The xUnit family has been extraordinarily successful at meeting its goals. I cannot imagine that Erich Gamma and Kent Beck could have possibly anticipated just how big an impact that first version of JUnit would have on software development! 3 The same characteristics that make xUnit particularly well suited to automating programmer tests, however, may make it less suitable for writing some other kinds of tests. In particular, the "stop on first failure" behavior of assertions in xUnit has often been criticized (or overridden) by people who want to use xUnit for automating multistep customer tests so that they can see the whole score (what worked and what didn't) rather than merely the first deviation from the expected results. This disagreement points out several things:
- "Stop on first failure" is a tool philosophy, not a characteristic of unit tests. It so happens that most test automaters prefer to have their unit tests stop on first failure, and most recognize that customer tests must necessarily be longer than unit tests.
- It is possible to change the fundamental behavior of xUnit to satisfy specific needs; this flexibility is just one advantage of open-source tools.
- Seeing a need to change the fundamental behavior of xUnit should probably be interpreted as a trigger for considering whether some other tool might possibly be a better fit.
For example, the Fit framework has been designed specifically for the purpose of running customer tests. It overcomes the limitations of xUnit that lead to the "stop on first failure" behavior by communicating the pass/fail status of each step of a test using color coding. Another option for Java developers is TestNG, which provides capabilities for explicitly sequencing Chained Tests (page 454 ).
Having said this, choosing a different tool doesn't eliminate the need to make many of the strategic decisions unless the tool constrains that decision making in some way. For example, we still need to set up the test fixture for a Fit test. Some patterns—such as Chained Tests , where one test sets up the fixture for a subsequent test—are difficult to automate and may therefore be less attractive in Fit than in xUnit. And isn't it ironic that the very flexibility of xUnit is what allows test automaters to get themselves into so much trouble by creating Obscure Tests (page 186 ) that result in High Test Maintenance Cost (page 265 )?
The xUnit Sweet Spot
The xUnit family works best when we can organize our tests as a large set of small tests, each of which requires a small test fixture that is relatively easy to set up. This allows us to create a separate test for each test scenario of each object. The test fixture should be managed using a Fresh Fixture (page 311 ) strategy by setting up a new Minimal Fixture (page 302 ) for each test.
xUnit works best when we write tests against software APIs and then test single classes or small groups of classes in isolation. This approach allows us to build small test fixtures that can be instantiated quickly.
When doing customer tests, xUnit works best if we define a Higher-Level Language (page 41 ) with which to describe our tests. This choice moves the level of abstraction higher, away from the nitty-gritty of the technology and closer to the business concepts that customers understand. From here, it is a very small step to convert these tests to Data-Driven Tests (page 288 ) implemented in xUnit or Fit.
Note that many of the higher-level patterns and principles described in this book apply equally well to both Fit tests and xUnit tests. I have also found them to be useful when working with commercial GUI-based testing tools, which typically use a "record and playback" metaphor. The fixture management patterns are particularly salient in this arena, as are reusable "test components" that may be strung together to form a variety of test scripts. This is entirely analogous to the xUnit practice of single-purpose Test Methods (page 348 ) calling reusable Test Utility Methods (page 599 ) to reduce their coupling to the SUT's API.
Which Test Fixture Strategy Do We Use?
The test fixture management strategy is strategic because it has a large impact on the execution time and robustness of the tests. The effects of picking the wrong strategy won't be felt immediately because it takes at least a few hundred tests before the Slow Tests (page 253 ) smell becomes evident and probably several months of development before the High Test Maintenance Cost smell starts to emerge. Once these smells appear, however, the need to change the test automation strategy will become apparent—and its cost will be significant because of the number of tests affected.
What Is a Fixture?
Every test consists of four parts, as described in Four-Phase Test (page 358 ). In the first phase, we create the SUT and everything it depends on and put them into the state required to exercise the SUT. In xUnit, we call everything we need in place to exercise the SUT the test fixture, and we call the part of the test logic that we execute to set it up the fixture setup phase of the test.
At this point, a word of caution is in order. The term "fixture" means many things to many people:
- Some variants of xUnit keep the concept of the fixture separate from the Testcase Class (page 373 ) that creates it. JUnit and its direct ports fall into this category.
- Other members of the xUnit family assume that an instance of the Testcase Class "is a" fixture. NUnit is a good example.
- A third camp uses an entirely different name for the fixture. For example, RSpec captures the pre-conditions of the test in a test context class that holds the Test Methods (same idea as NUnit but with different terminology).
- The term "fixture" is used to mean entirely different things in other kinds of test automation. In Fit, for example, it means the custom-built parts of the Data-Driven Test Interpreter [GOF] that we use to define our Higher-Level Language .
The "class 'is a' fixture" approach assumes the Testcase Class per Fixture (page 631 ) approach to organizing the tests. When we choose a different way of organizing the tests, such as Testcase Class per Class (page 617 ) or Testcase Class per Feature (page 624 ), this merging of the concepts of test fixture and Testcase Class can be confusing. Throughout this book, I use "test fixture"—or just "fixture"—to mean "the pre-conditions of the test" and Testcase Class to mean "the class that contains the Test Methods and any code needed to set up the test fixture."
The most common way to set up the fixture is to use front door fixture setup by calling the appropriate methods on the SUT to construct the objects. When the state of the SUT is stored in other objects or components, we can do Back Door Setup (see Back Door Manipulation on page 327 ) by inserting the necessary records directly into the other component on which the behavior of the SUT depends. We use Back Door Setup most often with databases or when we need to use a Mock Object (page 544 ) or Test Double (page 522 ); these concepts are covered in more detail in Chapter 13 , Testing with Databases, and Chapter 11 , Using Test Doubles .
Major Fixture Strategies
There are probably many ways to classify just about anything. For the purposes of this discussion, we will classify our test fixture strategies based on what kinds of test development work we need to do for each one.
The first and simplest fixture management strategy requires us to worry only how we will organize the code to build the fixture for each test. That is, do we put this code in our Test Methods , factor it into Test Utility Methods that we call from our Test Methods , or put it into a setUp method in our Testcase Class? This strategy involves the use of Transient Fresh Fixtures (see Fresh Fixture ). These fixtures live only in memory and very conveniently disappear as soon as we are done with them.
A second strategy involves the use of Fresh Fixtures that, for one reason or another, persist beyond the single Test Method that uses it. To keep them from turning into Shared Fixtures (page 317 ), these Persistent Fresh Fixtures (see Fresh Fixture ) require explicit code to tear them down at the end of each test. This requirement brings into play the fixture teardown patterns.
A third strategy involves persistent fixtures that are deliberately reused across many tests. This Shared Fixture strategy is often used to improve the execution speed of tests that use a Persistent Fresh Fixture but comes with a fair amount of baggage. These tests require the use of one of the fixture construction and teardown triggering patterns. They also involve tests that interact with one another, whether by design or by consequence, which often leads to Erratic Tests (page 228 ) and High Test Maintenance Costs .
Table 6.1 summarizes the fixture management overhead associated with each of the three styles of fixtures.
Table 6.1. A Summary of the Fixture Setup and Teardown Requirements of the Various Test Fixture Strategies
Note: The Shared Fixture row assumes we are building a new Shared Fixture each test run rather than using a Prebuilt Fixture (page 429 ).
Figure 6.4 illustrates the interaction between our goals, freshness of fixtures or fixture reuse, and fixture persistence. It also illustrates a few variations of the Shared Fixture .
Figure 6.4. A summary of the main test fixture strategies. Fresh Fixtures can be either transient or persistent; Shared Fixtures must be persistent. An Immutable Shared Fixture (see Shared Fixture) must not be modified by any test. As a consequence, most tests augment the Shared Fixture with a Fresh Fixture that they can modify.
The relationship between persistence and freshness is reasonably obvious for two of these combinations. The persistent Fresh Fixture is discussed in more detail later in this chapter. The transient Shared Fixture is inherently transient—how we hold references to these fixtures is what makes them persist. Other than this distinction, transient Shared Fixtures can be treated exactly like persistent Shared Fixtures .
Transient Fresh Fixtures
In this approach, each test creates a temporary Fresh Fixture as it runs. Any objects or records it requires are created by the test itself (though not necessarily inside the Test Method ). Because the test fixture visibility is restricted to the one test alone, we ensure that each test is completely independent because it cannot depend, either accidentally or on purpose, on the output of any other tests that use the same fixture.
We call this approach Fresh Fixture because each test starts with a clean slate and builds from there. It does not "inherit" or "reuse" any part of the fixture from other tests or from a Prebuilt Fixture (page 429 ). Every object or record used by the SUT is "fresh," "brand new," and not "previously enjoyed."
The main disadvantage of using the Fresh Fixture approach is the additional CPU cycles it takes to create all the objects for each test. As a consequence, the tests may run more slowly than under a Shared Fixture approach, especially if we use a Persistent Fresh Fixture .
Persistent Fresh Fixtures
A Persistent Fresh Fixture sounds a bit oxymoronic. We want the fixture to be fresh, yet it persists beyond the lifetime of a single test! What kind of strategy is that? Some might say "stupid," but sometimes one has to do this.
We are "forced" into this strategy when we are testing components that are tightly coupled to a database or other persistence mechanism. The obvious solution is that we should not let the coupling be so tight, but rather make the database a substitutable dependency of the component we are testing. This step may not be practical when testing legacy software, however—yet we may still want to partake of the benefits of a Fresh Fixture . Hence the existence of the Persistent Fresh Fixture strategy. The key difference between this strategy and the Transient Fresh Fixture is the need for code to tear down the fixture after each test. Persistent Fresh Fixtures can result in Slow Tests if the persistence of the fixture is caused by the use of a database, file system, or other high-latency dependency.
We can at least partially address the resulting Slow Tests by applying one or more of the following patterns:
- Construct a Minimal Fixture (the smallest fixture possible).
- Speed up the construction by using a Test Double to replace the provider of any data that takes too long to set up.
- If the tests still are not fast enough, minimize the size of the part of the fixture we need to destroy and reconstruct each time by using an Immutable Shared Fixture for any objects that are referenced but not modified.
The project teams with which I have worked have found that, on average, our tests run 50 times faster (yes, they take 2% as long) when we use Dependency Injection (page 678 ) or Dependency Lookup (page 686 ) to replace the entire database with a Fake Database (see Fake Object on page 551 ) that uses a set of hash tables instead of tables. Each test may require many, many database operations to set up and tear down the fixture required by a single query in the SUT.
There is a lot to be said for minimizing the size and complexity of the test fixture. A Minimal Fixture (see Minimal Fixture ) is much easier to understand and helps highlight the cause–effect relationship between the fixture and the expected outcome. In this regard, it is a major enabler of Tests as Documentation (page 23 ). In some cases, we can make the test fixture much smaller by using Entity Chain Snipping (see Test Stub on page 529 ) to eliminate the need to instantiate those objects on which our test depends only indirectly. This tactic will certainly speed up the instantiation of our test fixture.
Shared Fixture Strategies
Sometimes we cannot—or choose not to—use a Fresh Fixture strategy. In these cases, we can use a Shared Fixture . In this approach, many tests reuse the same instance of a test fixture.
The major advantage of Shared Fixtures is that we save a lot of execution time in setting up and tearing down the fixture. The main disadvantage is conveyed by one of its aliases, Stale Fixture, and by the test smell that describes its most common side effects, Interacting Tests (see Erratic Test ). Although Shared Fixtures do have other benefits, most can be realized by applying other patterns to Fresh Fixtures ; Standard Fixture (page 305 ) avoids the fixture design and coding effort for every test without actually sharing the fixture.
Now, if Shared Fixtures are so bad, why even discuss them? Because everyone seems to go down this road at least once in his or her career—so we might as well share the best available information about them should you venture down that path. Mind you, this discussion isn't meant to encourage anyone to go down this path unnecessarily because it is paved with broken glass, infested with poisonous snakes, and . . . well, you get my drift.
Given that we have decided to use a Shared Fixture (we did investigate every possible alternative, didn't we?), what are our options? We can make the following adjustments ( Figure 6.5 ):
- How far and wide we share a fixture (e.g., a Testcase Class , all tests in a test suite, all test run by a particular user)
- How often we recreate the fixture
Figure 6.5. The various ways we can manage a Shared Fixture. The strategies are ordered by the length of the fixture's lifetime, with the longestlasting fixture appearing on the left.
The more tests that share a fixture, the more likely that one of them will make a mess of things and spoil everything for all the tests that follow it. The less often we reconstruct the fixture, the longer the effects of a messed-up fixture will persist. For example, a Prebuilt Fixture can be set up outside the test run, thereby avoiding the entire cost of setting up the fixture as part of the test run; unfortunately, it can also result in Unrepeatable Tests (see Erratic Test ) if tests don't clean up after themselves properly. This strategy is most commonly used with a Database Sandbox (page 650 ) that is initialized using a database script; once the fixture is corrupted, it must be reinitialized by rerunning the script. If the Shared Fixture is accessible to more than one Test Runner (page 377 ), we may end up in a Test Run War (see Erratic Test ), in which tests fail randomly as they try to use the same fixture resource at the same time as some other test.
We can avoid both Unrepeatable Tests and Test Run Wars by setting up the fixture each time the test suite is run. xUnit provides several ways to do so, including Lazy Setup (page 435 ), Suite Fixture Setup (page 441 ), and Setup Decorator (page 447 ). The concept of "lazy initialization" should be familiar to most object-oriented developers; here we just apply the concept to the construction of the test fixture. The latter two choices provide a way to tear down the test fixture when the test run is finished because they call a setUp method and a corresponding tearDown at the appropriate times; Lazy Setup does not give us a way to do this.
Chained Tests represent another option for setting up a Shared Fixture , one that involves running the tests in a predefined order and letting each test use the previous test's results as its test fixture. Unfortunately, once one test fails, many of the tests that follow will provide erratic results because their pre-conditions have not been satisfied. This problem can be made easier to diagnose by having each test use Guard Assertions (page 490 ) to verify that its pre-conditions have been met. 4
As mentioned earlier, an Immutable Shared Fixture is a strategy for speeding up tests that use a Fresh Fixture . We can also use an Immutable Shared Fixture to make tests based on a Shared Fixture less erratic by restricting changes to a smaller, mutable part of a Shared Fixture .
How Do We Ensure Testability?
The last strategic concern touched on in this chapter is ensuring testability. The discussion here isn't intended to be a complete treatment of the topic—it is too large to cover in a single chapter on test strategy. Nevertheless, we shouldn't sweep this issue under the carpet either, because it definitely has a major impact on test automation. But first, I must climb onto my soapbox for a short digression into the development process.
Test Last—at Your Peril
Anyone who has tried to retrofit unit tests onto an existing application has probably experienced a lot of pain! This is the hardest kind of test automation we can do as well as the least productive. A lot of the benefit of automated tests is derived during the "debugging phase" of software development, when such tests can reduce the amount of time spent working with debugging tools. Tackling a test retrofit on legacy software as your first attempt at automated unit testing is the last thing you want to try, as it is sure to discourage even the most determined developers and project managers.
Design for Testability—Upfront
BDUF 5 design for testability is hard because it is difficult to know what the tests will need in the way of control points and observation points on the SUT. We can easily build software that is difficult to test. We can also spend a lot of time designing in testability mechanisms that are either insufficient or unnecessary. Either way, we will have spent a lot of effort with nothing to show for it.
Test-Driven Testability
The nice thing about building our software driven by tests is that we don't have to think very much about design for testability ; we just write the tests and that forces us to build for testability . The act of writing the test defines the control points and observation points that the SUT needs to provide. Once we have passed the tests, we know we have a testable design.
Now that I've done my bit promoting TDD as a "design for testability" process, let's get on with our discussion of the mechanics of actually making our software testable.
Control Points and Observation Points
A test interacts with the software 6 through one or more interfaces or interaction points . From the test's point of view, these interfaces can act as either control points or observation points ( Figure 6.6 ).
Figure 6.6. Control points and observation points. The test interacts with the SUT through interaction points. Direct interaction points are synchronous method calls made by the test; indirect interaction points require some form of Back Door Manipulation. Control points have arrows pointing toward the SUT; observation points have arrows pointing away from the SUT.
A control point is how the test asks the software to do something for it. This could be for the purpose of putting the software into a specific state as part of setting up or tearing down the test fixture, or it could be to exercise the SUT. Some control points are provided strictly for the tests; they should not be used by the production code because they bypass input validation or short-circuit the normal life cycle of the SUT or some object on which it depends.
An observation point is how the test finds out about the SUT's behavior during the result verification phase of the test. Observation points can be used to retrieve the post-test state of the SUT or a DOC. They can also be used to spy on the interactions between the SUT and any components with which it is expected to interact while it is being exercised. Verifying these indirect outputs is an example of Back Door Verification (see Back Door Manipulation ).
Both control points and observation points can be provided by the SUT as synchronous method calls; we call this "going in the front door." Some interaction points may be via a "back door" to the SUT; we call this Back Door Manipulation . In the diagrams that follow, control points are represented by the arrowheads that point to the SUT, whether from the test or from a DOC. Observation points are represented by the arrows whose heads point back to the test itself. These arrows typically start at the SUT or DOC 7 or start at the test and interact with either the SUT or DOC before returning to the test. 8
Interaction Styles and Testability Patterns
When testing a particular piece of software, our tests can take one of two basic forms.
A round-trip test interacts with the SUT in question only through its public interface—that is, its "front door" ( Figure 6.7 ). Both the control points and the observation points in a typical round-trip test are simple method calls. The nice thing about this approach is that it does not violate encapsulation. The test needs to know only the public interface of the software; it doesn't need to know anything about how it is built.
Figure 6.7. A round-trip test interacts with the SUT only via the front door. The test on the right replaces a DOC with a Fake Object to improve its repeatability or performance.
The main alternative is the layer-crossing test ( Figure 6.8 ), in which we exercise the SUT through the API and keep an eye on what comes out the back door using some form of Test Double such as a Test Spy (page 538 ) or Mock Object . This can be a very powerful testing technique for verifying certain kinds of mostly architectural requirements. Unfortunately, this approach can also result in Overspecified Software (see Fragile Test ) if it is overused because changes in how the software implements its responsibilities can cause tests to fail.
Figure 6.8. A layer-crossing test can interact with the SUT via a "back door." The test on the left controls the SUT's indirect inputs using a Test Stub. The test on the right verifies its indirect outputs using a Mock Object.
In Figure 6.8 , the test on the left uses a Test Stub that stands in for the DOC as a control point. The test on the right uses a Mock Object that stands in for the DOC as the observation point. Testing in this style implies a Layered Architecture [DDD, PEAA, WWW], which in turn opens the door to using Layer Tests (page 337 ) to test each layer of the architecture independently ( Figure 6.9 ). An even more general concept is the use of Component Tests (see Layer Test ) to test each component within a layer independently.
Figure 6.9. A pair of Layer Tests each testing a different layer of the system. Each layer of a layered architecture can be tested independently using a distinct set of Layer Tests. This ensures good separation of concerns, and the tests reinforce the layered architecture.
Whenever we want to write layer-crossing tests, we need to ensure that we have built in a substitutable dependency mechanism for any components on which the SUT depends but that we want to test independently. The leading contenders include any of the variations of Dependency Injection ( Figure 6.10 ) or some form of Dependency Lookup such as Object Factory or Service Locator . These dependency substitution mechanisms can be hand-coded or we can use an inversion of control (IOC) framework if one is available in our programming environment. The fallback plan is to use a Test-Specific Subclass (page 579 ) of the SUT or the DOC in question. This subclass can be used to override the dependency access or construction mechanism within the SUT or to replace the behavior of the DOC with test-specific behavior.
Figure 6.10. A Test Double being "injected" into a SUT by a test. A test can use Dependency Injection to replace a DOC with an appropriate Test Double. The DOC is passed to the SUT by the test as or after it has been created.
The "solution of last resort" is the Test Hook (page 709 ). 9 These constructs do have utility as temporary measures that allow us to automate tests to act as a Safety Net (page 24 ) while refactoring to retrofit testability. We definitely shouldn't make a habit of using them, however, as continued use of Test Hooks will result in Test Logic in Production (page 217 ).
A third kind of test worth mentioning is the asynchronous test, in which the test interacts with the SUT through real messaging. Because the responses to these requests also come asynchronously, these tests must include some kind of interprocess synchronization such as calls to wait . Unfortunately, the need to wait for message responses that might never arrive can cause these tests to take much, much longer to execute. This style of testing should be avoided at all costs in unit and component tests.
Fortunately, the Humble Executable pattern (see Humble Object on page 695 ) can remove the need to conduct unit tests this way ( Figure 6.11 ). It involves putting the logic that handles the incoming message into a separate class or component, which can then be tested synchronously using either a round-trip or layer-crossing style.
Figure 6.11. A Humble Executable making testing easier. The Humble Executable pattern can improve the repeatability and speed of verifying logic that would otherwise have to be verified via asynchronous tests.
A related issue is the testing of business logic through a UI. In general, such Indirect Testing (see Obscure Test ) is a bad idea because changes to the UI code will break tests that are trying to verify the business logic behind it. Because the UI tends to change frequently, especially on agile projects, this strategy will greatly increase test maintenance costs. Another reason this is a bad idea is that UIs are inherently asynchronous. Tests that exercise the system through the UI have to be asynchronous tests along with all the issues that come with them.
Divide and Test
We can turn almost any Hard-to-Test Code (page 209 ) into easily tested code through refactoring as long as we have enough tests in place to ensure that we do not introduce bugs during this refactoring.
We can avoid using the UI for customer tests by writing those tests as Subcutaneous Tests (see Layer Test ). These tests bypass the UI layer of the system and exercise the business logic via a Service Facade [CJ2EEP] that exposes the necessary synchronous interaction points to the test. The UI relies on the same facade, enabling us to verify that the business logic works correctly even before we hook up the UI logic. The layered architecture also enables us to test the UI logic before the business logic is finished; we can replace the Service Facade with a Test Double that provides completely deterministic behavior that our tests can depend on. 10
When conducting unit testing of nontrivial UIs, 11 we can use a Humble Dialog (see Humble Object ) to move the logic that makes decisions about the UI out of the visual layer, which is difficult to test synchronously, and into a layer of supporting objects, which can be verified with standard unit-testing techniques ( Figure 6.12 ). This approach allows the presentation logic behavior to be tested as thoroughly as the business logic behavior.
Figure 6.12. A Humble Dialog reducing the dependency of the test on the UI framework. The logic that controls the state of UI components can be very difficult to test. Extracting it into a testable component leaves behind a Humble Dialog that requires very little testing.
From a test automation strategy perspective, the key thing is to make the decision about which test–SUT interaction styles should be used and which ones should be avoided, and to ensure that the software is designed to support that decision.
What's Next?
This concludes our introduction to the hard-to-change decisions we must make as we settle upon our test automation strategy. Given that you are still reading, I will assume that you have decided xUnit is an appropriate tool for doing your test automation. The following chapters introduce the detailed patterns for implementing our chosen fixture strategy, whether it involves a Fresh Fixture or a Shared Fixture . First, we will explore the simplest case, a Transient Fresh Fixture, in Chapter 8 , Transient Fixture Management . We will then investigate the use of persistent fixtures in Chapter 9 , Persistent Fixture Management . But first, we must establish the basic xUnit terminology and notation that is used throughout this book in Chapter 7 , xUnit Basics .