Test Refactorings
Extract Testable Component
Also known as
Sprout Class [WEwLC]
You want to be able to test the logic easily but the component is too closely tied to its context to allow such testing.
Extract the logic you want to test into a separate component that is designed for testability and is independent of the context in which it is run.
Implementation Notes
We extract the logic from the untestable component into a component that is testable via synchronous tests, leaving behind all the ties to the context. This usually means that anything required by the testable component logic from the context is retrieved by the untestable component and passed in to the testable component as arguments of the methods under test or constructor methods. The untestable component then contains very little code and is considered to be a Humble Object (page 695 ). It simply retrieves the information the testable component requires from the context, instantiates the testable component, and delegates to it. All interactions with the new testable component consist of 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 untestable code may be an executable, a dialog box or some other presentation component, logic that is executed inside a transaction, or even a complex test method. Extraction of the testable component should leave behind a Humble Object that requires very little, if any, testing.
Depending on the nature of the untestable component, we may choose to write tests for the delegation logic or we may be unable to do so because the logic is so closely tied to the context. If we do write tests for it, we require only one or two tests to verify that the instantiation and delegation occur correctly. Because this code will not change very often, these tests are much less critical than other tests and can even be omitted from the suite of tests that developers execute before check-in if we want to speed up test suite execution times. Of course, we would still prefer to run them from the automated build process.
Further Reading
This refactoring is similar to an Extract Interface [Fowler] refactoring and an Extract Implementer [Fowler] refactoring, except that Extract Testable Component does not require keeping the same interface. It can also be viewed as a special case of the Extract Class [Fowler] refactoring.
In-line Resource
Tests that depend on an unseen external resource create a Mystery Guest problem.
Move the contents of an external resource into the fixture setup logic of the test.
From [RTC]:
To remove the dependency between a test method and some external resource, we incorporate that resource in the test code. This is done by setting up a fixture in the test code that holds the same contents as the resource. This fixture is then used instead of the resource to run the test. A simple example of this refactoring is putting the contents of a file that is used into some string in the test code.
If the contents of the resource are large, chances are high that you are also suffering from Eager Tests (see Assertion Roulette on page 224 ). Consider applying an Extract Method [Fowler] refactoring or a Minimize Data (page 738 ) refactoring.
Implementation Notes
The problem with tests that depend on an external resource is that we cannot see the pre-conditions of the test. The resource may be a file sitting in the file system, the contents of a database, or some other object created outside the test. None of these Prebuilt Fixtures (page 429 ) is visible to the test reader. The solution is to make them visible by including the resource in-line within the test. The simplest way to do so is to create the resource from within the test itself. For example, we could build the contents of a text file by writing to the file rather than just referring to a preexisting file. If we delete the file at the end of the test, this step also moves us from a Prebuilt Fixture approach to a Persistent Fresh Fixture (see Fresh Fixture on page 311 ) approach. As a result, our tests may execute somewhat more slowly.
A more innovative way to in-line the external resource is to replace the actual resource with a Test Stub (page 529 ) that is initialized within the test. The contents of the resource then become visible to the test reader. When the system under test (SUT) executes, it uses the Test Stub instead of the real resource.
Another option is to refactor the design of the SUT so as to improve its testability. We can apply the Extract Testable Component (page 735 ) refactoring to the part of the SUT that uses the contents of the resource so that it can be tested directly without actually accessing an external resource. That is, the test passes the contents of the resource to the logic that uses it. We can also test the Humble Object (page 695 ) that reads the resource independently by replacing the extracted component with a Test Stub or Mock Object (page 544 ).
Make Resource Unique
Several tests are accidentally creating or using the same resource in a Shared Fixture .
Make the name of any resources used by a test unique.
From [RTC]:
A lot of problems originate from the use of overlapping resource names, either between different tests run by the same user or between simultaneous test runs done by different users.
Such problems can easily be prevented (or repaired) by using unique identifiers for all resources that are allocated—for example, by including a time stamp. When you also include the name of the test responsible for allocating the resource in this identifier, you will have fewer problems finding tests that do not properly release their resources.
Implementation Notes
We make the name of any resources used by a test unique across all tests by using a Distinct Generated Value (see Generated Value on page 723 ) as part of the name. Ideally, the name should include the name of the test that "owns" the resource. To avoid Interacting Tests (see Erratic Test on page 228 ), we include a time stamp in the name of any resources created by the tests and use Automated Teardown (page 503 ) to delete those resources at the end of the test.
Minimize Data
Also known as
Reduce Data
The test fixture is too large, making the test hard to understand.
We remove things from the fixture until we have a Minimal Fixture.
From [RTC]:
Minimize the data that is set up in fixtures to the bare essentials. This will have two advantages: (1) It makes them more suitable as documentation, and (2) your tests will be less sensitive to changes.
Implementation Notes
Reducing the data in our test fixture to the bare minimum results in a Minimal Fixture (page 302 ) that helps the tests achieve Tests as Documentation (see page 23 ). How we do this depends on how our Test Methods (page 348 ) are organized into Testcase Classes (page 373 ).
When our Test Methods are organized via the Testcase Class per Fixture pattern (page 631 ) and we believe we have a General Fixture (see Obscure Test on page 186 ), we can remove the fixture setup logic for any parts of the fixture that we suspect are not used by the tests. It is best to remove this logic incrementally so that if a test fails, we can undo our most recent change and try again.
When our Test Methods are organized as a Testcase Class per Feature (page 624 ) or a Testcase Class per Class (page 617 ), Minimize Data may also involve copying fixture setup logic from the setUp method of a Testcase Class or Setup Decorator (page 447 ) into each test that needs the fixture. Assuming the collection of objects in the Shared Fixture (page 317 ) is overkill for any one test, we can use a series of Extract Method [Fowler] refactorings to create a set of Creation Methods (page 415 ), which we then call from the tests. Next, we remove the calls to the Creation Methods from the setUp method and put them into only those Test Methods that require that part of the original fixture. The final step would be to convert any fixture-holding instance variables into local variables.
Replace Dependency with Test Double
The dependencies of an object being tested get in the way of running tests.
Break the dependency by replacing a depended-on component with a Test Double.
Implementation Notes
The first step is to choose the form of dependency substitution. Dependency Injection (page 678 ) is the best option for unit tests, whereas Dependency Lookup (page 686 ) often works better for customer tests. We then refactor the SUT to support this choice or design the capability into the SUT as we do test-driven development. The next decision is whether to use a Fake Object (page 551 ), a Test Stub (page 529 ), a Test Spy (page 538 ), or a Mock Object (page 544 ) based on how the Test Double will be used by the test. This decision is described in Chapter 11 , Using Test Doubles .
If we are using a Test Stub or Mock Object , we must decide whether we want to use a Hard-Coded Test Double (page 568 ) or a Configurable Test Double (page 558 ). The trade-offs are discussed in Chapter 11 and in the detailed descriptions of the patterns. That decision then dictates the shape of our test—for example, Tests that use Mock Objects are more "front-loaded" by the construction of the Mock Object .
Finally, we modify our test to construct, optionally configure, and then install the Mock Object . We may also have to add a call to the verification method for some kinds of Mock Objects . In statically typed languages, we may have to do an Extract Interface [Fowler] refactoring before we can introduce the fake implementation. We then use this interface as the type of the variable that holds the reference to the substitutable dependency.
Setup External Resource
The SUT depends on the contents of an external resource that is acting as a Mystery Guest in our test.
Create an external resource within the fixture setup logic of the test rather than using a predefined resource.
From [RTC] :
If it is necessary for a test to rely on external resources, such as directories, databases, or files, make sure the test that uses them explicitly creates or allocates these resources before testing, and releases them when done (take precautions to ensure the resource is also released when tests fail).
Implementation Notes
When our SUT must use an external resource such as a file and we absolutely, positively cannot replace the access mechanism with a Test Stub (page 529 ) or Fake Object (page 551 ), we may need to live with the fact that we have to use an external resource. The problems with external resources are obvious: The test reader cannot tell what they contain; those resources may disappear unexpectedly, causing tests to fail because of Resource Optimism (see Erratic Test on page 228 ); and the resources may result in Interacting Tests (see Erratic Test ) and Test Run Wars (see Erratic Test ). Setup External Resource does not help us with the last problem but it does avoid the problems of a Mystery Guest (see Obscure Test on page 186 ) and Resource Optimism .
To implement the Setup External Resource refactoring, we simply pull the contents of the external resource into our Test Method (page 348 ), setUp method, or a Test Utility Method (page 599 ) called by them. Using the contents we construct the external resource within our test code, thereby making it evident to the test reader exactly what the test depends on. This approach also guarantees that the resource exists because we create it in every test run.