Transient Fixture Management
About This Chapter
Chapter 6 , Test Automation Strategy, looked at the strategic decisions that we need to make. That included the definition of the term "fixture" and the selection of a test fixture strategy. Chapter 7 , xUnit Basics, established our basic xUnit terminology and diagramming notation. This chapter builds on both of these earlier chapters by focusing on the mechanics of implementing the chosen fixture strategy.
There are several different ways to set up a Fresh Fixture (page 311 ), and our decision will affect how much effort it takes to write the tests, how much effort it takes to maintain our tests, and whether we achieve Tests as Documentation (see page 23 ). Persistent Fresh Fixtures (see Fresh Fixture ) are set up the same way as Transient Fresh Fixtures (see Fresh Fixture ) , albeit with some additional factors to consider related to fixture teardown ( Figure 8.1 ). Shared Fixtures (page 317 ) introduce another set of considerations. Persistent Fresh Fixtures and Shared Fixtures are discussed in detail in Chapter 9 .
Figure 8.1. Transient Fresh Fixture. Fresh Fixtures come in two flavors: Transient and Persistent. Both require fixture setup; the latter also requires fixture teardown.
Test Fixture Terminology
Before we can talk about setting up a fixture, we need to agree what a fixture is.
What Is a Fixture?
Every test consists of four parts, as described in Four-Phase Test (page 358 ). The first part is where we create the SUT and everything it depends on and where we put those elements 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 the part of the test logic that we execute to set it up the fixture setup .
The most common way to set up the fixture is using front door fixture setup—that is, to call the appropriate methods on the SUT to put it into the starting state. This may require constructing other objects and passing them to the SUT as arguments of method calls. 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 )—that is, we can insert 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 possibilities are covered in Chapter 13 , Testing with Databases, and Chapter 11 , Using Test Doubles, respectively.
It is worth noting that the term "fixture" is used to mean different things in different kinds of test automation. The xUnit variants for the Microsoft languages call the Testcase Class (page 373 ) the test fixture. Most other variants of xUnit distinguish between the Testcase Class and the test fixture (or test context) it sets up. In Fit [FitB] , the term "fixture" is used to mean the custom-built parts of the Data-Driven Test (page 288 ) interpreter that we use to define our Higher-Level Language (see page 41 ). Whenever this book says "test fixture" without further qualifying this term, it refers to the stuff we set up before exercising the SUT. To refer to the class that hosts the Test Methods (page 348 ), whether it be in Java or C#, Ruby or VB, this book uses Testcase Class .
What Is a Fresh Fixture?
In a Fresh Fixture strategy, we set up a brand-new fixture for every test we run ( Figure 8.2 ). That is, each Testcase Object (page 382 ) builds its own fixture before exercising the SUT and does so every time it is rerun. That is what makes the fixture "fresh." As a result, we completely avoid the problems associated with Interacting Tests (see Erratic Test on page 228 ).
Figure 8.2. A pair of Fresh Fixtures, each with its creator. A Fresh Fixture is built specifically for a single test, used once, and then retired.
What Is a Transient Fresh Fixture?
When our fixture is an in-memory fixture referenced only by local variables or instance variables, 1 the fixture just "disappears" after every test courtesy of Garbage-Collected Teardown (page 500 ). When fixtures are persistent, this is not the case. Thus we have some decisions to make about how we implement the Fresh Fixture strategy. In particular, we have two different ways to keep them "fresh." The obvious option is tear down the fixture after each test. The less obvious option is to leave the old fixture around and then build a new fixture in such a way that it does not collide with the old fixture.
Most Fresh Fixtures we build are transient, so we will cover that case first. We will then come back to managing Persistent Fresh Fixtures in Chapter 9 .
Building Fresh Fixtures
Whether we are building a Transient Fresh Fixture or a Persistent Fresh Fixture , the choices we have for how to construct it are pretty much the same. The fixture setup logic includes the code needed to instantiate the SUT, 2 the code to put the SUT into the appropriate starting state, and the code to create and initialize the state of anything the SUT depends on or that will be passed to it as an argument. The most obvious way to set up a Fresh Fixture is through In-line Setup (page 408 ), in which all fixture setup logic is contained within the Test Method . This type of fixture can also be constructed by using Delegated Setup (page 411 ), which involves calling Test Utility Methods (page 599 ). Finally, we can use Implicit Setup (page 424 ), in which the Test Automation Framework (page 298 ) calls a special setUp method we provide on our Testcase Class . We can also use a combination of these three approaches. Let's look at each possibility individually.
In-line Fixture Setup
In In-line Setup , the test handles all of the fixture setup within the body of the Test Method . We construct objects, call methods on them, construct the SUT, and call methods on it to put into a specific state. We perform all of these tasks from within our Test Method . Think of In-line Setup as the do-it-yourself approach to fixture creation.
public void testStatus_initial() {
// In-line setup
Airport departureAirport = new Airport("Calgary", "YYC");
Airport destinationAirport = new Airport("Toronto", "YYZ");
Flight flight = new Flight ( flightNumber,
departureAirport,
destinationAirport);
// Exercise SUT and verify outcome
assertEquals(FlightState.PROPOSED, flight.getStatus());
// tearDown:
// Garbage-collected
}
The main drawback of In-line Setup is that it tends to lead to Test Code Duplication (page 213 ) because each Test Method needs to construct the SUT. Many of the Test Methods also need to perform similar fixture setup. This Test Code Duplication leads, in turn, to High Test Maintenance Cost (page 265 ) caused by Fragile Tests (page 239 ). If the work to create the fixture is complex, it can also lead to Obscure Tests (page 186 ). A related problem is that In-line Setup tends to encourage Hard-Coded Test Data (see Obscure Test ) within each Test Method because creating a local variable with an Intent-Revealing Name [SBPP] may seem like too much work for the benefit yielded.
We can prevent these test smells by moving the code that sets up the fixture out of the Test Method . The location where we move it determines which of the alternative fixture setup strategies we have used.
Delegated Fixture Setup
A quick and easy way to reduce Test Code Duplication and the resulting Obscure Tests is to refactor our Test Methods to use Delegated Setup . We can use an Extract Method [Fowler] refactoring to move a sequence of statements used in several Test Methods into a Test Utility Method that we then call from those Test Methods . This is a very simple and safe refactoring, especially when we let the IDE do all the heavy lifting for us. When the extracted method contains logic to create an object on which our test depends, we call it a Creation Method (page 415 ). Creation Methods 3 with Intent-Revealing Names make the test's pre-conditions readily apparent to the reader while avoiding unnecessary Test Code Duplication . They allow both the test reader and the test automater to focus on what is being created without being distracted by how it is created. The Creation Methods act as reusable building blocks for test fixture construction.
public void testGetStatus_inital() {
// Setup
Flight flight = createAnonymousFlight();
// Exercise SUT and verify outcome
assertEquals(FlightState.PROPOSED, flight.getStatus());
// Teardown
// Garbage-collected
}
One goal of these Creation Methods is to eliminate the need for every test to know the details of how the objects it requires are created. This streamlining goes a long way toward preventing Fragile Tests caused by changes to constructor method signatures or semantics. When a test does not care about the specific identity of the objects it is creating, we can use Anonymous Creation Methods (see Creation Method ). These methods generate any unique keys required by the object being created. By using a Distinct Generated Value (see Generated Value on page 723 ) , we can guarantee that no other test instance that requires a similar object will accidentally use the same object as this test. This safeguard prevents many forms of the behavior smell Erratic Test, including Unrepeatable Tests , Interacting Tests, and Test Run Wars, even if we happen to be using a persistent object repository that supports Shared Fixtures .
When a test does care about the attributes of the object being created, we use a Parameterized Anonymous Creation Method (see Creation Method ) . This method is passed any attributes that the test cares about (i.e., attributes that are important to the test outcome), leaving all other attributes to be defaulted by the implementation of the Creation Method . My motto is this:
When it is not important for something to be seen in the test method, it is important that it not be seen in the test method!
Delegated Setup is often used when we write input validation tests for SUT methods that are expected to validate the attributes of an object argument. In such a case, we need to write a separate test for each invalid attribute that should be detected. Building all of these slightly invalid objects would be a lot of work using In-line Setup . We can reduce the effort and the amount of Test Code Duplication dramatically by using the pattern One Bad Attribute (see Derived Value on page 718 ). That is, we first call a Creation Method to create a valid object, and then we replace one attribute with an invalid value that should be rejected by the SUT. Similarly, we might create an object in the correct state by using a Named State Reaching Method (see Creation Method ).
Some people prefer to Reuse Tests for Fixture Setup (see Creation Method ) as an alternative to using Chained Tests (page 454 ). That is, they call other tests directly within the setup portion of their test. This approach is not an unreasonable one as long as the test reader can readily identify what the other test is setting up for the current test. Unfortunately, very few tests are named in such a way as to convey this intention. For this reason, if we value Tests as Documentation , we will want to consider wrapping the called test with a Creation Method that has an Intent-Revealing Name so that test reader can get a sense of what the fixture looks like.
The Creation Methods can be kept as private methods on the Testcase Class , pulled up to a Testcase Superclass (page 638 ), or moved to a Test Helper (page 643 ). The "mother of all creation methods" is Object Mother (see Test Helper ). This strategy-level pattern describes a family of approaches that center on the use of Creation Methods on one or more Test Helpers and may include Automated Teardown (page 503 ) as well.
Implicit Fixture Setup
Most members of the xUnit family provide a convenient hook for calling code that needs to be run before every Test Method . Some members call a method with a specific name (e.g., setUp ). Others call a method that has a specific annotation (e.g., "@before" in JUnit) or method attribute (e.g., "[ Setup ]" in NUnit). To avoid repeating these alternative ways every time we need to refer to this mechanism, this book simply calls it the setUp method regardless of how we indicate this fact to the Test Automation Framework . The setUp method is optional or an empty default implementation is provided by the framework, so we do not have to provide one in each Testcase Class .
In Implicit Setup, we take advantage of this framework "hook" by putting all of the fixture creation logic into the setUp method. Because every Test Method on the Testcase Class shares this fixture setup logic, all Test Methods need to be able to use the fixture it creates. This tactic certainly addresses the Test Code Duplication problem but it does have several consequences. What does the following test actually verify?
Airport departureAirport;
Airport destinationAirport;
Flight flight;
public void testGetStatus_inital() {
// Implicit setup
// Exercise SUT and verify outcome
assertEquals(FlightState.PROPOSED, flight.getStatus());
}
The first consequence is that this approach can make the tests more difficult to understand because we cannot see how the pre-conditions of the test (the test fixture) correlate with the expected outcome within the Test Method ; we have to look in the setUp method to see this relationship.
public void setUp() throws Exception{
super.setUp();
departureAirport = new Airport("Calgary", "YYC");
destinationAirport = new Airport("Toronto", "YYZ");
BigDecimal flightNumber = new BigDecimal("999");
flight = new Flight( flightNumber , departureAirport,
destinationAirport);
}
We can mitigate this problem by naming our Testcase Class based on the test fixture created in the setUp method. Of course, this makes sense only if all of the Test Methods really need the same fixture—it is an example of Testcase Class per Fixture (page 631 ). As mentioned earlier, several members of the xUnit family (VbUnit and NUnit, to name two) use the term "test fixture" to describe what this book calls the Testcase Class . This nomenclature is probably based on the assumption that we are using a Testcase Class per Fixture strategy.
Another consequence of using Implicit Setup is that we cannot use local variables to hold references to the objects in our fixture. Instead, we are forced to use instance variables to refer to any objects that are constructed in the setUp method and that are needed either when exercising the SUT, when verifying the expected outcome, or when tearing down the fixture. These instance variables act as global variables between the parts of the test. As long as we stick to instance variables rather than class variables, however, the test fixture will be newly constructed for each test case in the Testcase Class . Most members of xUnit provide isolation between the fixture created for each Test Method but at least one (NUnit) does not; see the sidebar " There's Always an Exception " (page 384 ) for more information. In any event, we should definitely give the variables Intent-Revealing Names so that we do not need to keep referring back to the setUp method to understand what they hold.
Misuse of the SetUp Method
When you have a new hammer, everything looks like a nail!
Like any feature of any system, the setUp method can be abused. We should not feel obligated to use it just because it is provided. It is one of several code reuse mechanisms that are available for our application. When object-oriented languages were first introduced, programmers were enamored with inheritance and tried to apply it in all possible reuse scenarios. Over time, we learned when inheritance was appropriate and when we should resort to other mechanisms such as delegation. The setUp method is xUnit's inheritance.
The setUp method is most prone to misuse when it is applied to build a General Fixture (see Obscure Test ) with multiple distinct parts, each of which is dedicated to a different Test Method . This can lead to Slow Tests (page 253 ) if we are building a Persistent Fresh Fixture. More importantly, it can lead to Obscure Tests by hiding the cause–effect relationship between the fixture and the expected outcome of exercising the SUT.
If we do not adopt the practice of grouping the Test Methods into Testcase Classes based on identical fixtures but we do use the setUp method, we should build only the lowest common denominator part of the fixture in the setUp method. That is, only the setup logic that will not cause problems in any of the tests should be placed in the setUp method. Even the fixture setup code that does not cause problems for any of the Test Methods can still cause other problems if we use the setUp method to build a General Fixture instead of a Minimal Fixture (page 302 ). A General Fixture is a common cause of Slow Tests because each test spends much more time than necessary building the test fixture. It also tends to produce Obscure Tests because the test reader cannot easily see which part of the fixture a particular Test Method depends on. A General Fixture often evolves into a Fragile Fixture (see Fragile Test ) as the relationship between its various elements and the tests that use them is forgotten over time. Changes made to the fixture to support a newly added test may then cause existing tests to fail.
Note that if we use a class variable to hold the object, we may have crossed the line into the world of Persistent Fresh Fixtures. Use of Lazy Setup (page 435 ) to populate the variable, by contrast, carries us into the world of Shared Fixtures because later tests within the test suite may reuse the object(s) created in earlier tests and thus may become dependent on the changes the other test (should have) made to it.
Hybrid Fixture Setup
This chapter has presented the three styles of fixture construction as strict alternatives to one another. In practice, there is value in combining them. Test automaters often call some Creation Methods from within the Test Method but then do some additional setup on an in-line basis. The readability of the setUp method can also be improved if it calls Creation Methods to construct the fixture. An additional benefit is that the Creation Methods can be unit-tested much more easily than either in-line fixture construction logic or the setUp method. These methods can also be located on a class outside the Testcase Class hierarchy such as a Test Helper .
Tearing Down Transient Fresh Fixtures
One really nice thing about Transient Fresh Fixtures is that fixture teardown requires very little effort. Most members of the xUnit family are implemented in languages that support garbage collection . As long as our references to the fixture are held in variables that go out of scope, we can count on Garbage-Collected Teardown to do all the work for us. See the sidebar " There's Always an Exception " on page 384 for a description of why the same is not true in NUnit.
If we are using one of the few members of the xUnit family that does not support garbage collection, we may have to treat all Fresh Fixtures as persistent.
What's Next?
This chapter introduced techniques for setting up and tearing down an in-memory Fresh Fixture . With some planning and a bit of luck, they are all you should need for the majority of your tests. Managing Fresh Fixtures is more complicated when the fixture is persisted either by the SUT or by the test itself. Chapter 9 , Persistent Fixture Management , introduces additional techniques needed for managing persistent fixtures, including Persistent Fresh Fixtures and Shared Fixtures .