Test Strategy Patterns

Patterns in This Chapter

Test Automation Strategy

       Recorded Test 278

       Scripted Test 285

       Data-Driven Test 288

       Test Automation Framework 298

Test Fixture Strategy

       Minimal Fixture 302

       Standard Fixture 305

       Fresh Fixture 311

       Shared Fixture 317

SUT Interaction Strategy

       Back Door Manipulation 327

       Layer Test 337

Recorded Test

Also known as

Record and Playback Test, Robot User Test, Capture/Playback Test

How do we prepare automated tests for our software?

We automate tests by recording interactions with the application and playing them back using a test tool.

image

Automated tests serve several purposes. They can be used for regression testing software after it has been changed. They can help document the behavior of the software. They can specify the behavior of the software before it has been written. How we prepare the automated test scripts affects which purposes they can be used for, how robust they are to changes in the SUT, and how much skill and effort it takes to prepare them.

Recorded Tests allow us to rapidly create regression tests after the SUT has been built and before it is changed.

How It Works

We use a tool that monitors our interactions with the SUT as we work with it. This tool keeps track of most of what the SUT communicates to us and our responses to the SUT. When the recording session is done, we can save the session to a file for later playback. When we are ready to run the test, we start up the "playback" part of the tool and point it at the recorded session. It starts up the SUT and feeds it our recorded inputs in response to the SUT's outputs. It may also compare the SUT's outputs with the SUT's responses during the recording session. A mismatch may be cause for failing the test.

Some Recorded Test tools allow us to adjust the sensitivity of the comparisons that the tool makes between what the SUT said during the recording session and what it said during the playback. Most Recorded Test tools interact with the SUT through the user interface.

When to Use It

Once an application is up and running and we don't expect a lot of changes to it, we can use Recorded Tests to do regression testing. We could also use Recorded Tests when an existing application needs to be refactored (in anticipation of modifying the functionality) and we do not have Scripted Tests (page 285 ) available to use as regression tests. It is typically much quicker to produce a set of Recorded Tests than to prepare Scripted Tests for the same functionality. In theory, the test recording can be done by anyone who knows how to operate the application; very little technical expertise should be required. In practice, many of the commercial tools have a steep learning curve. Also, some technical expertise may be required to add "checkpoints," to adjust the sensitivity of the playback tool, or to adjust the test script if the recording tool became confused and recorded the wrong information.

Most Recorded Test tools interact with the SUT through the user interface. This approach makes them particularly prone to fragility if the user interface of the SUT is evolving ( Interface Sensitivity ; see Fragile Test on page 239 ). Even small changes such as changing the internal name of a button or field may be enough to cause the playback tool to stumble. The tools also tend to record information at a very low and detailed level, making the tests hard to understand ( Obscure Test ; page 186 ); as a result, they are also difficult to repair by hand if they are broken by changes to the SUT. For these reasons, we should plan on rerecording the tests fairly regularly if the SUT will continue to evolve.

If we want to use the Tests as Documentation (see page 23 ) or if we want to use the tests to drive new development, we should consider using Scripted Tests . These goals are difficult to address with commercial Recorded Test tools because most do not let us define a Higher-Level Language (see page 41 ) for the test recording. This issue can be addressed by building the Recorded Test capability into the application itself or by using Refactored Recorded Test .

Variation: Refactored Recorded Test

A hybrid of the two strategies is to use the "record, refactor, playback" 1 sequence to extract a set of "action components" or "verbs" from the newly Recorded Tests and then rewire the test cases to call these "action components" instead of having detailed in-line code. Most commercial capture/replay tools provide the means to turn Literal Values (page 714 ) into parameters that can be passed into the "action component" by the main test case. When a screen changes, we simply rerecord the "action component"; all the test cases continue to function by automatically using the new "action component" definition. This strategy is effectively the same as using Test Utility Methods (page 599 ) to interact with the SUT in unit tests. It opens the door to using the Refactored Recorded Test components as a Higher-Level Language in Scripted Tests . Tools such as Mercury Interactive's BPT 2 use this paradigm for scripting tests in a top-down manner; once the high-level scripts are developed and the components required for the test steps are specified, more technical people can either record or hand-code the individual components.

Implementation Notes

We have two basic choices when using a Recorded Test strategy: We can either acquire third-party tools that record the communication that occurs while we interact with the application or we can build a "record and playback" mechanism right into our application.

Variation: External Test Recording

Many test recording tools are available commercially, each of which has its own strengths and weaknesses. The best choice will depend on the nature of the user interface of the application, our budget, the complexity of the functionality to be verified, and possibly other factors.

If we want to use the tests to drive development, we need to pick a tool that uses a test-recording file format that is editable by hand and easily understood. We'll need to handcraft the contents—this situation is really an example of a Scripted Test even if we are using a "record and playback" tool to execute the tests.

Variation: Built-In Test Recording

It is also possible to build a Recorded Test capability into the SUT. In such a case, the test scripting "language" can be defined at a fairly high level—high enough to make it possible to hand-script the tests even before the system is built. In fact, it has been reported that the VBA macro capability of Microsoft's Excel spreadsheet started out as a mechanism for automated testing of Excel.

Example: Built-In Test Recording

On the surface, it doesn't seem to make sense to provide a code sample for a Recorded Test because this pattern deals with how the test is produced, not how it is represented. When the test is played back, it is in effect a Data-Driven Test (page 288 ). Likewise, we don't often refactor to a Recorded Test because it is often the first test automation strategy attempted on a project. Nevertheless, we might introduce a Recorded Test after attempting Scripted Tests if we discover that we have too many Missing Tests (page 268 ) because the cost of manual automation is too high. In that case, we would not be trying to turn existing Scripted Tests into Recorded Tests ; we would just record new tests.

Here's an example of a test recorded by the application itself. This test was used to regression-test a safety-critical application after it was ported from C on OS2 to C++ on Windows. Note how the recorded information forms a domain-specific Higher-Level Language that is quite readable by a user.

                                                             5566                                                                                                           SOUTH                                                    SOUTH                             NORTH                                                                         SOUTH                           NORTH                                                              

This sample depicts the output of having played back the tests. The actual elements were inserted by the built-in playback mechanism. The status attributes indicate whether these elements match the expected values. We applied a style sheet to these files to format them much like a Fit test with color-coded results. The business users on the project then handled the recording, replaying, and result analysis.

This recording was made by inserting hooks in the presentation layer of the software to record the lists of choices offered the user and the user's responses. An example of one of these hooks follows:

if  (playback_is_on())  {
    choice  =  get_choice_for_playback(dialog_id,  choices_list);
}  else  {
    choice    =  display_dialog(choices_list,  row,  col,  title,  key);
}

if  (recording_is_on())    {
    record_choice(dialog_id,  choices_list,  choice,  key);
}

The method get_choice_for_playback retrieves the contents of the used-value element instead of asking the user to pick from the list of choices. The method record_choice generates the actual element and makes the "assertions" against the expected elements, recording the result in the status attribute of each element. Note that recording_is_on() returns true whenever we are in playback mode so that the test results can be recorded.

Example: Commercial Record and Playback Test Tool

Almost every commercial testing tool uses a "record and playback" metaphor. Each tool also defines its own Recorded Test file format, most of which are very verbose. The following is a "short" excerpt from a test recorded using Mercury Interactive's QuickTest Professional [ QTP ] tool. It is shown in "Expert View," which exposes what is really recorded: a VbScript program! The example includes comments (preceded by "@@") that were inserted manually to clarify what this test is doing; these comments would be lost if the test were rerecorded after a change to the application caused the test to no longer run.

@@
@@  GoToPageMaintainTaxonomy()
@@
Browser("Inf").Page("Inf").WebButton("Login").Click
Browser("Inf").Page("Inf_2").Check  CheckPoint("Inf_2")
Browser("Inf").Page("Inf_2"").Link("TAXONOMY  LINKING").Click
Browser("Inf").Page("Inf_3").Check  CheckPoint("Inf_3")
Browser("Inf").Page("Inf_3").Link("MAINTAIN  TAXONOMY").Click
Browser("Inf").Page("Inf_4").Check  CheckPoint("Inf_4")
@@
@@  AddTerm("A","Top  Level",  "Top  Level  Definition")
@@
Browser("Inf").Page("Inf_4").Link("Add").Click
wait  4
Browser("Inf_2").Page("Inf").Check  CheckPoint("Inf_5")
Browser("Inf_2").Page("Inf").WebEdit("childCodeSuffix").Set  "A"
Browser("Inf_2").Page("Inf").
     WebEdit("taxonomyDto.descript").Set  "Top  Level"
Browser("Inf_2").Page("Inf").
     WebEdit("taxonomyDto.definiti").Set  "Top  Level  Definition"
Browser("Inf_2").Page("Inf").WebButton("Save").Click
wait  4
Browser("Inf").Page("Inf_5").Check  CheckPoint("Inf_5_2")
@@
@@  SelectTerm("[A]-Top  Level")
@@
Browser("Inf").Page("Inf_5").
     WebList("selectedTaxonomyCode").Select  "[A]-Top  Level"
@@
@@  AddTerm("B","Second  Top  Level",  "Second  Top  Level  Definition")
@@
Browser("Inf").Page("Inf_5").Link("Add").Click
wait  4
Browser("Inf_2").Page("Inf_2").Check  CheckPoint("Inf_2_2")
      infofile_;_Inform_Alberta_21.inf_;_hightlight  id_;
          _Browser("Inf_2").Page("Inf_2")_;_
@@
@@  and  it  goes  on,  and  on,  and  on  ....

Note how the test describes all inputs and outputs in terms of the user interface of the application. It suffers from two main issues: Obscure Tests (caused by the detailed nature of the recorded information) and Interface Sensitivity (resulting in Fragile Tests ).

Refactoring Notes

We can make this test more useful as documentation, reduce or avoid High Test Maintenance Cost (page 265 ), and support composition of other tests from a Higher-Level Language by using a series of Extract Method [Fowler] refactorings.

Example: Refactored Commercial Recorded Test

The following example shows the same test refactored to Communicate Intent (see page 41 ):

GoToPage_MaintainTaxonomy()
AddTerm("A","Top  Level",  "Top  Level  Definition")
SelectTerm("[A]-Top  Level")
AddTerm("B","Second  Top  Level",  "Second  Top  Level  Definition")

Note how much more intent revealing this test has become. The Test Utility Methods we extracted look like this:

Method  GoToPage_MaintainTaxonomy()
      Browser("Inf").Page("Inf").WebButton("Login").Click
      Browser("Inf").Page("Inf_2").Check  CheckPoint("Inf_2")
      Browser("Inf").Page("Inf_2").Link("TAXONOMY  LINKING").Click
      Browser("Inf").Page("Inf_3").Check  CheckPoint("Inf_3")
      Browser("Inf").Page("Inf_3").Link("MAINTAIN  TAXONOMY").Click
      Browser("Inf").Page("Inf_4").Check  CheckPoint("Inf_4")
End

Method  AddTerm(  code,  name,  description)
      Browser("Inf").Page("Inf_4").Link("Add").Click
      wait  4
      Browser("Inf_2").Page("Inf").Check  CheckPoint("Inf_5")
      Browser("Inf_2").Page("Inf").
           WebEdit("childCodeSuffix").Set  code
      Browser("Inf_2").Page("Inf").
           WebEdit("taxonomyDto.descript").Set  name
      Browser("Inf_2").Page("Inf").
           WebEdit("taxonomyDto.definiti").Set  description
      Browser("Inf_2").Page("Inf").WebButton("Save").Click
      wait  4
      Browser("Inf").Page("Inf_5").Check  CheckPoint("Inf_5_2")
end

Method  SelectTerm(  path  )
      Browser("Inf").Page("Inf_5").
           WebList("selectedTaxonomyCode").Select  path
      Browser("Inf").Page("Inf_5").Link("Add").Click
      wait  4
end

This example is one I hacked together to illustrate the similarities to what we do in xUnit. Don't try running this example at home—it is probably not syntactically correct.

Further Reading

The paper "Agile Regression Testing Using Record and Playback" [ARTRP] describes our experiences building a Recorded Test mechanism into an application to facilitate porting it to another platform.

Scripted Test

Also known as

Hand-Written Test, Hand-Scripted Test, Programmatic Test, Automated Unit Test

How do we prepare automated tests for our software?

We automate the tests by writing test programs by hand.

image

Automated tests serve several purposes. They can be used for regression testing software after it has been changed. They can help document the behavior of the software. They can specify the behavior of the software before it has been written. How we prepare the automated test scripts affects which purpose they can be used for, how robust they are to changes in the SUT, and how much skill and effort it takes to prepare them.

Scripted Tests allow us to prepare our tests before the software is developed so they can help drive the design.

How It Works

We automate our tests by writing test programs that interact with the SUT for the purpose of exercising its functionality. Unlike Recorded Tests (page 278 ), these tests can be either customer tests or unit tests. These test programs are often called "test scripts" to distinguish them from the production code they test.

When to Use It

We almost always use Scripted Tests when preparing unit tests for our software. This is because it is easier to access the individual units directly from software written in the same programming language. It also allows us to exercise all the code paths, including the "pathological" cases.

Customer tests are a slightly more complicated picture; we should use a Scripted Test whenever we use automated storytests to drive the development of software. Recorded Tests don't serve this need very well because it is difficult to record tests without having an application from which to record them. Preparing Scripted Tests takes programming experience as well as experience in testing techniques. It is unlikely that most business users on a project would be interested in learning how to prepare Scripted Tests . An alternative to scripting tests in a programming language is to define a Higher-Level Language (see page 41 ) for testing the SUT and then to implement the language as a Data-Driven Test (page 288 ) Interpreter [GOF] . An open-source framework for defining Data-Driven Tests is Fit and its wiki-based cousin, FitNesse. Canoo WebTest is another tool that supports this style of testing.

In case of an existing legacy application, 3 we can consider using Recorded Tests as a way of quickly creating a suite of regression tests that will protect us while we refactor the code to introduce testability. We can then prepare Scripted Tests for our now testable application.

Implementation Notes

Traditionally, Scripted Tests were written as "test programs," often using a special test scripting language. Nowadays, we prefer to write Scripted Tests using a Test Automation Framework (page 298 ) such as xUnit in the same language as the SUT. In this case, each test program is typically captured in the form of a Test Method (page 348 ) on a Testcase Class (page 373 ). To minimize Manual Intervention (page 250 ), each test method should implement a Self-Checking Test (see page 26 ) that is also a Repeatable Test (see page 26 ).

Example: Scripted Test

The following is an example of a Scripted Tests written in JUnit:

public  void  testAddLineItem_quantityOne(){
      final  BigDecimal  BASE_PRICE  =  UNIT_PRICE;
      final  BigDecimal  EXTENDED_PRICE  =  BASE_PRICE;
      //    Set  Up  Fixture
      Customer  customer  =  createACustomer(NO_CUST_DISCOUNT);
      Invoice  invoice  =  createInvoice(customer);
      //     Exercise  SUT
      invoice.addItemQuantity(PRODUCT,  QUAN_ONE);
      //  Verify  Outcome
      LineItem  expected  =
          createLineItem(  QUAN_ONE,  NO_CUST_DISCOUNT,
                                     EXTENDED_PRICE,  PRODUCT,  invoice);
      assertContainsExactlyOneLineItem(  invoice,  expected  );
}

public  void  testChangeQuantity_severalQuantity(){
      final  int  ORIGINAL_QUANTITY  =  3;
      final  int  NEW_QUANTITY  =  5;
      final  BigDecimal  BASE_PRICE  =
              UNIT_PRICE.multiply(      new  BigDecimal(NEW_QUANTITY));
      final  BigDecimal  EXTENDED_PRICE  =
              BASE_PRICE.subtract(BASE_PRICE.multiply(
                                      CUST_DISCOUNT_PC.movePointLeft(2)));
      //          Set  Up  Fixture
      Customer  customer  =  createACustomer(CUST_DISCOUNT_PC);
      Invoice  invoice  =  createInvoice(customer);
      Product  product  =  createAProduct(  UNIT_PRICE);
      invoice.addItemQuantity(product,  ORIGINAL_QUANTITY);
      //  Exercise  SUT
      invoice.changeQuantityForProduct(product,  NEW_QUANTITY);
      //  Verify  Outcome
      LineItem  expected  =  createLineItem(  NEW_QUANTITY,
          CUST_DISCOUNT_PC,  EXTENDED_PRICE,  PRODUCT,  invoice);
      assertContainsExactlyOneLineItem(  invoice,  expected  );
}

About the Name

Automated test programs are traditionally called "test scripts," probably due to the heritage of such test programs—originally they were implemented in interpreted test scripting languages such as Tcl. The downside of calling them Scripted Tests is that this nomenclature opens the door to confusion with the kind of script a person would follow during manual testing as opposed to unscripted testing such as exploratory testing .

Further Reading

Many books have been written about the process of writing Scripted Tests and using them to drive the design of the SUT. A good place to start would be [TDD-BE] or [TDD-APG].

Data-Driven Test

How do we prepare automated tests for our software?
How do we reduce Test Code Duplication?

We store all the information needed for each test in a data file and write an interpreter that reads the file and executes the tests.

image

Testing can be very repetitious not only because we must run the same test over and over again, but also because many of the tests differ only slightly. For example, we might want to run essentially the same test with slightly different system inputs and verify that the actual output varies accordingly. Each of these tests would consist of exactly the same steps. While having so many tests is an excellent way to ensure good coverage of functionality, it is not so good for test maintainability because any change made to the algorithm of one of these tests must be propagated to all of the similar tests.

A Data-Driven Test is one way to get excellent coverage while minimizing the amount of test code we need to write and maintain.

How It Works

We write a Data-Driven Test interpreter that contains all the common logic from the tests. We put the data that varies from test to test into the Data-Driven Test file that the interpreter reads to execute the tests. For each test it performs the same sequence of actions to implement the Four-Phase Test (page 358 ). First, the interpreter retrieves the test data from the file and sets up the test fixture using the data from the file. Second, it exercises the SUT with whatever arguments the file specifies. Third, it compares the actual results produced by the SUT (e.g., returned values, post-test state) with the expected results from the file. If the results don't match, it marks the test as failed; if the SUT throws an exception, it catches the exception and marks the test accordingly and continues. Fourth, the interpreter does any fixture teardown that is necessary and then moves on to the next test in the file.

A test that might otherwise require a series of complex steps can be reduced to a single line of data in the Data-Driven Test file. Fit is a popular example of a framework for writing Data-Driven Tests .

When to Use It

A Data-Driven Test is an alternative strategy to a Recorded Test (page 278 ) and a Scripted Test (page 285 ). It can also be used as part of a Scripted Test strategy, however, and Recorded Tests are, in fact, Data-Driven Tests when they are played back. A Data-Driven Test is an ideal strategy for getting business people involved in writing automated tests. By keeping the format of the data file simple, we make it possible for the business person to populate the file with data and execute the tests without having to ask a technical person to write test code for each test.

We can consider using a Data-Driven Test as part of a Scripted Test strategy whenever we have a lot of different data values with which we wish to exercise the SUT where the same sequence of steps must be executed for each data value. Usually, we discover this similarity over time and refactor first to a Parameterized Test (page 607 ) and then to a Data-Driven Test . We may also want to arrange a standard set of steps in different sequences with different data values much like in an Incremental Tabular Test (see Parameterized Test ). This approach gives us the best coverage with the least amount of test code to maintain and makes it very easy to add more tests as they are needed.

Another consideration when deciding whether to use Data-Driven Tests is whether the behavior we are testing is hard-coded or driven by configuration data. If we automate tests for data-driven behavior using Scripted Tests , we must update the test programs whenever the configuration data changes. This behavior is just plain unnatural because it implies that we must commit changes to our source code repository [SCM] whenever we change the data in our configuration database. 4 By making the tests data-driven, changes to the configuration data or meta-objects are then driven by changes to the Data-Driven Tests— a much more natural relationship.

Implementation Notes

Our implementation options depend on whether we are using a Data-Driven Test as a distinct test strategy or as part of an xUnit-based strategy. Using a Data-Driven Test as a stand-alone test strategy typically involves using open-source tools such as Fit or commercial Recorded Test tools such as QTP. Using a Data-Driven Test as part of a Scripted Test strategy may involve implementing a Data-Driven Test interpreter within xUnit.

Regardless of which strategy we elect to follow, we should use the appropriate Test Automation Framework (page 298 ) if one is available. By doing so, we effectively convert our tests into two parts: the Data-Driven Test interpreter and the Data-Driven Test files. Both of these assets should be kept under version control so that we can see how they have evolved over time and to allow us to back out any misguided changes. It is particularly important to store the Data-Driven Test files in some kind of Repository, even though this concept may be foreign to business users. We can make this operation transparent by providing the users with a Data-Driven Test file-authoring tool such as FitNesse, or we can set up a "user-friendly" Repository such as a document management system that just happens to support version control as well.

It is also important to run these tests as part of the continuous integration process to confirm that tests that once passed do not suddenly begin to fail. Failing to do so can result in bugs creeping into the software undetected and significant troubleshooting effort once the bugs are detected. Including the customer tests in the continuous integration process requires some way to keep track of which customer tests were already passing, because we don't insist that all customer tests pass before any code is committed. One option is to keep two sets of input files, migrating tests that pass from the "still red" file into the "all green" file that is used for regression testing as part of the automatic build process.

Variation: Data-Driven Test Framework (Fit)

We should consider using a prebuilt Data-Driven Test framework when we are using Data-Driven Tests as a test strategy. Fit is a framework originally conceived by Ward Cunningham as a way of involving business users in the automation of tests. Although Fit is typically used to automate customer tests, it can also be used for unit tests if the number of tests warrants building the necessary fixtures. Fit consists of two parts: the framework and a user-created fixture. The Fit Framework is a generic Data-Driven Test interpreter that reads the input file and finds all tables in it. It looks in the top-left cell of each table for a fixture classname and then searches our test executable for that class. When it finds a class, it creates an instance of the class and passes control to that instance as it reads each row and column of the table. We can override methods defined by the framework to specify what should happen for each cell in the table. A Fit fixture, then, is an adapter that Fit calls to interpret a table of data and invoke methods on the SUT.

The Fit table can also contain expected results from the SUT. Fit compares the specified values with the actual values returned by the SUT. Unlike Assertion Methods (page 362 ) in xUnit, however, Fit does not abandon a test at the first value that does not match the expected value. Instead, it colors in each cell in the table, with green cells indicating actual values that matched the expected values and red cells indicating wrong or unexpected values.

Using Fit offers several advantages:

  • There is much less code to write than when we build our own test Interpreter [GOF] .
  • The output makes sense to a business person, not just a technical person.
  • The tests don't stop at the first failed assertion. Fit has a way of communicating multiple failures/errors in a way that allows us to see the failure patterns very easily.
  • There are a plethora of fixture types available to subclass or use as is.

So why wouldn't we use Fit for all our unit testing instead of xUnit? The main disadvantages of using Fit are described here:

  • The test scenarios need to be very well understood before we can build the Fit fixture. We then need to translate each test's logic into a tabular representation; this isn't always a good fit, especially for developers who are used to thinking procedurally. While it may be appropriate to have testers who can write the Fit fixtures for customer tests, this approach wouldn't be appropriate for true unit tests unless we had close to a 1:1 tester-to-developer ratio.
  • The tests need to employ the same SUT interaction logic in each test. 5 To run several different styles of tests, we would probably have to build one or more different fixtures for each style of test. Building a new fixture is typically more complex than writing a few Test Methods (page 348 ).

Although many different fixture types are available to subclass or use as is, their use in this way is yet another thing that developers would be required to learn to do their jobs. Even then, not all unit tests are amenable to automation using Fit.

  • Fit tests aren't normally integrated into developers' regression tests that are run via xUnit. Instead, these tests must be run separately—which introduces the possibility that they will not be run at each check-in. Some teams include Fit tests as part of their continuous integration build process to partially mitigate this issue. Other teams have reported great success having a second "customer" build service or server that runs all the customer tests.

Each of these issues is potentially surmountable, of course. In general, xUnit is a more appropriate framework for unit testing than Fit; the reverse is true for customer tests.

Variation: Naive xUnit Test Interpreter

When we have a small number of Data-Driven Tests that we wish to run as part of an xUnit-based Scripted Test strategy, the simplest implementation is to write a Test Method containing a loop that reads one set of input data values from the file along with the expected results. This is the equivalent of converting a single Parameterized Test and all its callers into a Tabular Test (see Parameterized Test ). As with a Tabular Test , this approach to building the Data-Driven Test interpreter will result in a single Testcase Object (page 382 ) with many assertions. This has several ramifications:

  • The entire set of Data-Driven Tests will count as a single test. Hence, converting a set of Parameterized Tests into a single Data-Driven Test will reduce the count of tests executed.
  • We will stop executing the Data-Driven Test on the first failure or error. As a consequence, we will lose a lot of our Defect Localization (see page 22 ). Some variants of xUnit do allow us to specify that failed assertions shouldn't abort execution of the Test Method.
  • We need to make sure our assertion failures tell us which subtest we were executing when the failure occurred.

We could address the last two issues by including a try/catch statement inside the loop but surrounding the test logic and then continuing the code's execution. Nevertheless, we still need to find a way to report the test results in a meaningful way (e.g., "Failed subtests 1, 3, and 6 with . . .").

To make it easier to extend the Data-Driven Test interpreter to handle several different kinds of tests in the same data file, we can include a "verb" or "action word" as part of each entry in the data file. The interpreter can then dispatch to a different Parameterized Test based on the action word.

Variation: Test Suite Object Generator

We can avoid the "stop on first failure" problem associated with a Naive xUnit Test Interpreter by having the suite method on the Test Suite Factory (see Test Enumeration on page 399 ) fabricate the same Test Suite Object (page 387 ) structure as the built-in mechanism for Test Discovery (page 393 ). To do so, we build a Testcase Object for each entry in the Data-Driven Test file and initialize each object with the test data for the particular test. 6 That object knows how to execute the Parameterized Test with the data loaded into it when the test suite was built. This ensures that the Data-Driven Test continues executing even after the first Testcase Object encounters an assertion failure. We can then let the Test Runner (page 377 ) count the tests, errors, and failures in the normal way.

Variation: Test Suite Object Simulator

An alternative to building the Test Suite Object is to create a Testcase Object that behaves like one. This object reads the Data-Driven Test file and iterates over all the tests when asked to run. It must catch any exceptions thrown by the Parameterized Test and continue executing the subsequent tests. When finished, the Testcase Object must report the correct number of tests, failures, and errors back to the Test Runner . It also needs to implement any other methods on the standard test interface on which the Test Runner depends, such as returning the number of tests in the "suite," returning the name and status of each test in the suite (for the Graphical Test Tree Explorer, see Test Runner ), and so forth.

Motivating Example

Let's assume we have a set of tests as follows:

def  test_extref
        sourceXml  =  "<extref  id='abc'  />"
        expectedHtml  =  "<a  href='abc.html'>abc</a>"
        generateAndVerifyHtml(sourceXml,expectedHtml,"<extref>")
end

def  test_testterm_normal
    sourceXml  =  "<testterm  id='abc'/>"
    expectedHtml  =  "<a  href='abc.html'>abc</a>"
    generateAndVerifyHtml(sourceXml,expectedHtml,"<testterm>")
end

def  test_testterm_plural
    sourceXml  =  "<testterms  id='abc'/>"
    expectedHtml  =  "<a  href='abc.html'>abcs</a>"
    generateAndVerifyHtml(sourceXml,expectedHtml,"<plural>")
end

The succinctness of these tests is made possible by defining the Parameterized Test as follows:

def  generateAndVerifyHtml(  sourceXml,  expectedHtml,
                                      message,  &block)
    mockFile  =  MockFile.new
    sourceXml.delete!("\t")
    @handler  =  setupHandler(sourceXml,  mockFile  )
    block.call  unless  block  ==  nil
    @handler.printBodyContents
    actual_html  =  mockFile.output
    assert_equal_html(  expectedHtml,
                                  actual_html,
                                  message  +  "html  output")
      actual_html
end

The main problem with these tests is that they are still written in code when, in fact, the only difference between them is the data used as input.

Refactoring Notes

The solution, of course, is to extract the common logic of the Parameterized Tests into a Data-Driven Test interpreter and to collect all sets of parameters into a single data file that can be edited by anyone. We need to write a "main" test that knows which file to read the test data from and a bit of logic to read and parse the test file. This logic can call our existing Parameterized Test logic and let xUnit keep track of the test execution statistics for us.

Example: xUnit Data-Driven Test with XML Data File

In this example, we will use XML as our file representation. Each test consists of a test element with three main parts:

  • An action that tells the Data-Driven Test interpreter which test logic to run (e.g., crossref )
  • The input to be passed to the SUT—in this case, the sourceXml element
  • The HTML we expect the SUT to produce (in the expectedHtml element)

These three components are wrapped up in a testsuite element.

<testsuite  id="CrossRefHandlerTest">
    <test  id="extref">
        <action>crossref</action>
        <sourceXml>
              <extref  id='abc'/>
        </sourceXml>
        <expectedHtml>
              <a  href='abc.html'>abc</a>
        </expectedHtml>
    </test>
    <test  id="TestTerm">
        <action>crossref</action>
        <sourceXml>
              <testterm  id='abc'/>
        </sourceXml>
        <expectedHtml>
              <a  href='abc.html'>abc</a>
        </expectedHtml>
    </test>
    <test  id="TestTerm  Plural">
        <action>crossref</action>
        <sourceXml>
              <testterms  id='abc'/>
        </sourceXml>
        <expectedHtml>
              <a  href='abc.html'>abcs</a>
        </expectedHtml>
    </test>

This XML file could be edited by anyone with an XML editor without any concern for introducing test logic errors. All the logic for verifying the expected outcome is encapsulated by the Data-Driven Test interpreter in much the same way as it would be by a Parameterized Test . For viewing purposes we could hide the XML structure from the user by defining a style sheet. In addition, many XML editors will turn the XML into a form-based input to simplify editing.

To avoid dealing with the complexities of manipulating XML, the interpreter can also use a CSV file as input.

Example: xUnit Data-Driven Test with CSV Input File

The test in the previous example would look like this as a CSV file:

ID,    Action,         SourceXml,           ExpectedHtml
Extref,crossref,<extref  id='abc'/>,<a  href='abc.html'>abc</a>
TTerm,crossref,<testterm  id='abc'/>,<a  href='abc.html'>abc</a>
TTerms,crossref,<testterms  id='abc'/>,<a  href='abc.html'>abcs</a>

The interpreter is relatively simple and is built on the logic we had already developed for our Parameterized Test . This version reads the CSV file and uses Ruby's split function to parse each line.

def  test_crossref
    executeDataDrivenTest  "CrossrefHandlerTest.txt"
end

def  executeDataDrivenTest  filename
    dataFile  =  File.open(filename)
    dataFile.each_line  do  |  line  |
        desc,  action,  part2  =  line.split(",")
          sourceXml,  expectedHtml,  leftOver  =  part2.split(",")
            if  "crossref"==action.strip
              generateAndVerifyHtml  sourceXml,  expectedHtml,  desc
        else  #  new  "verbs"  go  before  here  as  elsif's
              report_error(  "unknown  action"  +  action.strip  )
        end
    end
end

Unless we changed the implementation of generateAndVerifyHtml to catch assertion failures and increment a failure counter, this Data-Driven Test will stop executing at the first failed assertion. While this behavior would be acceptable for regression testing, it would not provide very good Defect Localization .

Example: Data-Driven Test Using Fit Framework

If we wanted to have even more control over what the user can do, we could create a Fit "column fixture" with the columns "id," "action," "source XML," and "expected Html()" and let the user edit an HTML Web page instead ( Figure 18.1 ).

Figure 18.1. A Data-Driven test built using the Fit framework.

image

When using Fit, the test interpreter is the Fit framework extended by the Fit fixture class specific to the test:

public  class  CrossrefHandlerFixture  extends  ColumnFixture  {
      //  Input  columns
      public  String  id;
      public  String  action;
      public  String  sourceXML;

      //  Output  columns
      public  String  expectedHtml()  {
            return  generateHtml(sourceXML);
      }
}

The methods of this fixture class are called by the Fit framework for each cell in each line in the Fit table based on the column headers. Simple names are interpreted as the instance variable of the fixture (e.g., "id," "source XML"). Column names ending in "()" signify a function that Fit calls and then compares its result with the contents of the cell.

The resulting output is shown in Figure 18.2 . This colored-in table allows us to get an overview of the results of running one file of tests at a single glance.

Figure 18.2. The results of executing the Fit test.

image

Test Automation Framework

How do we make it easy to write and run tests written by different people?

We use a framework that provides all the mechanisms needed to run the test logic so the test writer needs to provide only the test-specific logic.

image

Writing and running automated tests involves several steps, but many of these steps are the same for every test. If every test had to include an implementation of these steps, writing automated tests would be very tedious, time-consuming, prone to errors, and expensive.

Using a Test Automation Framework is a way to minimize the effort of writing Fully Automated Tests (see page 26 ).

How It Works

We build a framework that implements all the mechanisms required to run suites of tests and record the results. These mechanisms include the ability to find individual tests, assemble them into a test suite, execute each test in turn, verify expected outcomes, collect and report any test failures or errors, and clean up when failures or errors do occur. The framework provides a way to plug in and run the test-specific behavior that test automaters write.

Why We Do This

Building Fully Automated Tests that are repeatable and robust is a much more complicated process than just writing a test script that invokes the SUT. We need to handle success cases and error cases, both expected and unexpected. We need to set up and tear down test fixtures . We need to specify which test(s) to run. We also need to report on the results after we have run a suite of tests.

The amount of effort required to build Fully Automated Tests can act as a serious deterrent to automation of tests. We can reduce the cost of getting started significantly by providing a framework that implements the most common functionality—the only entry cost is then incurred while learning to use the framework. This cost, in turn, can be reduced if the framework implements a common protocol such as xUnit that makes it easier for us to learn a second or third framework once we have experience with the first.

Using a framework also helps isolate the implementation of the logic required to run the tests from the logic of the tests. This approach can help reduce Test Code Duplication (page 213 ) and minimize the occurrence of Obscure Tests (page 186 ). It also ensures that test written by different test automaters can be run easily in a single test run with a single report on the test results .

Implementation Notes

Many kinds of Test Automation Frameworks are available, from both commercial vendors and open-source resources. They can be classified into two main categories: "robot user" test tools and Scripted Tests (page 285 ). The latter category can be further subdivided into the xUnit and Data-Driven Tests (page 288 ) families of Test Automation Frameworks .

Variation: Robot User Test Frameworks

A large number of third-party test automation tools are designed to test applications via the user interface. Most of them use the "record and playback" test metaphor. This metaphor leads to some very seductive marketing materials, because it makes test automation seem as simple as running some tests manually while recording the test session. Such a robot user test tool consists of two major parts: the "test recorder," which monitors and records the interactions between the user and the SUT, and the "test runner," which executes the Recorded Tests (page 278 ). Most of these test automation tools are also frameworks that support a number of "widget recognizer" plug-ins. Most commercial tools come with a gaggle of built-in widget recognizers.

Variation: The xUnit Family of Test Automation Frameworks

Most unit-testing tools belong to the xUnit family of testing frameworks designed for automating Hand-Scripted Tests (see Scripted Test ). xUnit has been ported to (or developed from scratch for) most current programming languages. The xUnit family of unit-testing frameworks consists of several major components. The most visible is the Test Runner (page 377 ), which can be invoked either from the command line or as a Graphical Test Runner (see Test Runner ). It builds the Testcase Objects (page 382 ), collects them into Test Suite Objects (page 387 ), and invokes each of the Test Methods (page 348 ). The other major component of the xUnit frameworks is the library of built-in Assertion Methods (page 362 ) that are used within the Test Methods to specify the expected outcome of each test.

Variation: Data-Driven Test Frameworks

A Data-Driven Test framework provides a way to plug in interpreters that know how to execute a specific kind of test step. This flexibility, in effect, extends the format of the input file with new "verbs" and objects. Such a framework also provides a test runner that reads in the file, passes control to the plug-ins when their corresponding data formats are encountered, and keeps track of statistics for the test run. The most notable member of the Data-Driven Test Frameworks family is Fit, which enables test automaters to write tests in tabular form and to "plug in" fixture classes that know how to interpret specific formats of tables.

Example: Test Automation Framework

The Test Automation Framework looks somewhat different for each of the possible ways to automate tests. To see these variations, refer to Recorded Test , Scripted Test, and Data-Driven Test for examples of the respective Test Automation Frameworks .

Further Reading

Some of the more popular examples of Test Automation Frameworks for xUnit are JUnit (Java), SUnit (Smalltalk), CppUnit (C++), NUnit (all .NET languages), runit (Ruby), PyUnit (Python), and VbUnit (Visual Basic). A more complete and up-to-date list can be found at http://xprogramming.com , along with a list of the available extensions (e.g., HttpUnit, Cactus).

Other open-source Test Automation Frameworks include Fit, Canoo WebTest, and Watir . Commercial Test Automation Frameworks include QTP, BPT, and eCATT, among many others.

In Test-Driven Development—By Example [TDD-BE], Kent Beck illustrates TDD by building a Test Automation Framework in Python. In an approach he likens to "doing brain surgery on yourself," he uses the emerging Test Automation Framework to run the tests he writes for each new capability. This application is a very good example of both TDD and bootstrapping.

Minimal Fixture

Also known as

Minimal Context

Which fixture strategy should we use?

We use the smallest and simplest fixture possible for each test.

image

Every test needs some kind of test fixture. A key part of understanding a test is understanding the test fixture and recognizing how it influences the expected outcome of the test. Tests are much easier to understand if the fixture is small and simple.

Why We Do This

A Minimal Fixture is important for achieving Tests as Documentation (see page 23 ) and for avoiding Slow Tests (page 253 ). A test that uses a Minimal Fixture will always be easier to understand than one that uses a fixture containing unnecessary or irrelevant information. This is true whether we are using a Fresh Fixture (page 311 ) or a Shared Fixture (page 317 ), although the effort to build a Minimal Fixture is typically higher with a Shared Fixture because it must be designed to handle several tests. Defining a Minimal Fixture is much easier for a Fresh Fixture because it need serve only a single test.

Implementation Notes

We design a fixture that includes only those objects that are absolutely necessary to express the behavior that the test verifies. Another way to phrase this is "If the object is not important to understand the test, it is important not to include it in the fixture."

To build a Minimal Fixture , we ruthlessly remove anything from the fixture that does not help the test communicate how the SUT should behave. Two forms of "minimization" can be considered:

  • We can eliminate objects entirely. That is, we don't even build the objects as part of the fixture. If the object isn't necessary to prove something about how the SUT behaves, we don't include it at all.
  • We can hide unnecessary attributes of the object when they don't contribute to the understanding of the expected behavior.

A simple way to find out whether an object is necessary as part of the fixture is to remove it. If the test fails as a result, the object was probably necessary in some way . Of course, it may have been necessary only as an argument to some method we are not interested in or as an attribute that is never used (even though the object to which the attribute belongs is required for some reason). Including these kinds of objects as part of fixture setup definitely contributes to Obscure Tests (page 186 ). We can eliminate these unnecessary objects in one of two ways: (1) by hiding them or (2) by eliminating the need for them by passing in Dummy Objects (page 728 ) or using Entity Chain Snipping (see Test Stub on page 529 ). If the SUT actually accesses the object as it is executing the logic under test, however, we may be forced to include the object as part of the test fixture.

Having determined that the object is necessary for the execution of the test, we must now ask whether the object is helpful in understanding the test. If we were to initialize it "off-stage," would that make it harder to understand the test? Would the object lead to an Obscure Test by acting as a Mystery Guest (see Obscure Test )? If so, we want to keep the object visible. Boundary values are a good example of a case in which we do want to keep the objects and attributes that take on the boundary values visible.

If we have established that the object or attribute isn't necessary for understanding the test, we should make every effort to eliminate it from the Test Method (page 348 ), albeit not necessarily from the test fixture. Creation Methods (page 415 ) are a common way of achieving this goal. We can hide the attributes of objects that don't affect the outcome of the test but that are needed for construction of the object by using Creation Methods to fill in all the "don't care" attributes with meaningful default values. We can also hide the creation of necessary depended-on objects within the Creation Methods . A good example of this occurs when we write tests that require badly formed objects as input (for testing the SUT with invalid inputs). In this case we don't want to confuse the issue by showing all valid attributes of the object being passed to the SUT; there could be many of these extraneous attributes. Instead, we want to focus on the invalid attribute. To do so, we can use the One Bad Attribute pattern (see Derived Value on page 718 ) to build malformed objects with a minimum of code by calling a Creation Method to construct a valid object and then replacing a single attribute with the invalid value that we want to verify the SUT will handle correctly.

Standard Fixture

Also known as

Standard Context

Which fixture strategy should we use?

We reuse the design of the test fixture across the many tests.

image

To execute an automated test, we require a text fixture that is well understood and completely deterministic. Designing a custom test fixture for each test requires extra effort. A Standard Fixture offers a way to reuse the same fixture design in several tests without necessarily sharing the same fixture instance .

How It Works

A Standard Fixture is more about attitude than about technology. It requires us to decide early on in the testing process that we will design a Standard Fixture that can be used by several or many tests rather than mining a common fixture from tests that were designed independently. In a sense, a Standard Fixture is the result of "Big Design Upfront" of the test fixture for a whole suite of tests. We then define our specific tests using this common test fixture design.

The choice of a Standard Fixture is independent of the choice between a Fresh Fixture (page 311 ) and a Shared Fixture (page 317 ). A Shared Fixture is, by definition, a Standard Fixture. The reverse is not true, however, because a Standard Fixture focuses on reuse of the fixture's design —not the time when the fixture is built or its visibility. Having chosen to use a Standard Fixture , we still need to decide whether each test will build its own instance of the Standard Fixture (a Fresh Fixture ) or whether we will build it once as a Shared Fixture and reuse it across many tests.

When to Use It

When I was reviewing an early draft of this book with Series Editor Martin Fowler, he asked me, "Do people actually do this?" This question exemplifies the philosophical divide of fixture design. Coming from an agile background, Martin lets each test pull a fixture into existence. If several tests happen to need the same fixture, then it makes sense to factor it out into the setUp method and split the class into one Testcase Class per Fixture (page 631 ). It doesn't even occur to Martin to design a Standard Fixture that all tests can use. So who uses them?

Standard Fixtures are something of a tradition in the testing (quality assessment) community. It is very commonplace to define a large Standard Fixture that is then used as a test bed for testing activities. This approach makes a lot of sense in the context of manual execution of many customer tests because it eliminates the need for each tester to spend a lot of time setting up the test environment for each customer test and it allows several testers to work in the same test environment at the same time. Some test automaters also use Standard Fixtures when defining their automated customer tests. This strategy is especially prevalent when test automaters use a Shared Fixture, for obvious reasons.

In the xUnit community, use of a Standard Fixture simply to avoid designing a Minimal Fixture (page 302 ) for each test is considered undesirable and has been given the name General Fixture (see Obscure Test on page 186 ). A more accepted example is the use of Implicit Setup (page 424 ) in conjunction with Testcase Class per Fixture because only a few Test Methods (page 348 ) share the design of the fixture and they do so because they need the same design. As we make a Standard Fixture more reusable across many tests with disparate needs, it tends to grow larger and more complex. This trend can lead to a Fragile Fixture (see Fragile Test on page 239 ) as the needs of new tests introduce changes that break existing clients of the Standard Fixture . Depending on how we go about building the Standard Fixture , we may also find ourselves entertaining a Mystery Guest (see Obscure Test ) if the cause–effect relationships between the fixture and outcome are not easy to discern either because the fixture setup is hidden from the test or because it is not clear which characteristics of the referenced part of the Standard Fixture serve as pre-conditions for the test.

A Standard Fixture will also take longer to build than a Minimal Fixture because there is more fixture to construct. When we are building a Fresh Fixture for each Testcase Object (page 382 ), this effort can lead to Slow Tests (page 253 ), especially if the fixture setup involves a database. (See the sidebar " Unit Test Rulz " for an opinion about what kinds of behavior are acceptable for a unit test.) For these reasons, we may be better off using a Minimal Fixture to avoid the extra fixture setup overhead associated with creating objects that are only needed in other tests.


Unit Test Rulz

Michael Feathers of Object Mentor writes:

I've used these rules with a large number of teams. They encourage good design and rapid feedback and they seem to help teams avoid a lot of trouble.
A test is not a unit test if:

  • It talks to the database.
  • It communicates across the network.
  • It touches the file system.
  • It can't run correctly at the same time as any of your other unit tests.
  • You have to do special things to your environment (such as editing config files) to run it.

Tests that do these things aren't bad. Often they are worth writing, and they can be written in a unit test harness. However, it is important to be able to separate them from true unit tests so that we can keep a set of tests that we can run fast whenever we make our changes.

http://www.objectmentor.com


Implementation Notes

As mentioned earlier, we can use a Standard Fixture as either a Fresh Fixture or a Shared Fixture, and we can set it up using either Implicit Setup or Delegated Setup (page 411 ). 7 When using it as a Fresh Fixture , we can define a Test Utility Method (page 599 ) (function or procedure) that builds the Standard Fixture ; we can then call the Test Utility Method from each test that needs this particular design of fixture. Alternatively, we can take advantage of xUnit support for Implicit Setup by putting all of the fixture construction logic in the setUp method.

When building a Standard Fixture for use as a Shared Fixture , we can employ any of the Shared Fixture setup patterns including Suite Fixture Setup (page 441 ), Lazy Setup (page 435 ), and Setup Decorator (page 447 ).

Motivating Example

As mentioned earlier, we are most likely to end up using a Standard Fixture because we started that way—and we probably started that way as the result of the background of one of the project participants. We probably would not refactor our tests to use a Standard Fixture when those tests are already written to use a Minimal Fixture unless we were refactoring to create a Testcase Class per Fixture . For the sake of illustration, let's assume that we did want to get to "here" from "there." The following example uses Creation Methods (page 415 ) to build a custom Fresh Fixture for each test:

public  void  testGetFlightsByFromAirport_OneOutboundFlight_c()
              throws  Exception  {
      FlightDto  outboundFlight  =  createOneOutboundFlightDto();
      //  Exercise  System
      List  flightsAtOrigin  =
                facade.getFlightsByOriginAirport(
                                        outboundFlight.getOriginAirportId());
      //  Verify  Outcome
      assertOnly1FlightInDtoList(  "Flights  at  origin",
                                                outboundFlight,
                                                flightsAtOrigin);
}

public  void  testGetFlightsByFromAirport_TwoOutboundFlights_c()
              throws  Exception  {
      FlightDto[]  outboundFlights  =
        createTwoOutboundFlightsFromOneAirport();
      //  Exercise  System
      List  flightsAtOrigin  =  facade.getFlightsByOriginAirport(
                              outboundFlights[0].getOriginAirportId());
      //  Verify  Outcome
      assertExactly2FlightsInDtoList(  "Flights  at  origin",
                                                   outboundFlights,
                                                   flightsAtOrigin);
}

To keep this test short, we have used Delegated Setup to populate the SUT with the Minimal Fixture needed for each test. We could have included the fixture setup code in-line in each method, but that choice would take us down the road toward an Obscure Test .

Refactoring Notes

Technically speaking, converting a pile of tests to a Standard Fixture isn't really a "refactoring" because we actually change the behavior of these tests. The biggest challenge is designing the reusable Standard Fixture in such a way that each Test Method can find some part of the fixture that serves its needs. This means synthesizing all of the individual purpose-built Minimal Fixtures into a single "jack of all trades" fixture. Not surprisingly, this reworking of the code can be a nontrivial exercise when we have a lot of tests.

The easy and mechanical part of the refactoring is to convert the logic in each test that constructs the fixture into calls to Finder Methods (see Test Utility Method ) that retrieve the appropriate part of the Standard Fixture . This transformation is most easily done as a series of steps. First, we extract the in-line fixture construction logic in each Test Method into one or more Creation Methods with Intent-Revealing Names [SBPP] . Next, we do a global replace on the "create" part of each call to "find." Finally, we generate (either manually or using our IDE's "quick fix" capability) the Finder Methods needed to get the calls to compile. Inside each Finder Methods we add in code to return the relevant part of the Standard Fixture .

Example: Standard Fixture

Here's the example given earlier converted to use a Standard Fixture :

public  void  testGetFlightsByFromAirport_OneOutboundFlight()
                throws  Exception  {
      setupStandardAirportsAndFlights();
      FlightDto  outboundFlight  =  findOneOutboundFlight();
      //  Exercise  System
      List  flightsAtOrigin  =  facade.getFlightsByOriginAirport(
                           outboundFlight.getOriginAirportId());
      //  Verify  Outcome
      assertOnly1FlightInDtoList(  "Flights  at  origin",
                                               outboundFlight,
                                               flightsAtOrigin);
}

public  void  testGetFlightsByFromAirport_TwoOutboundFlights()
                throws  Exception  {
      setupStandardAirportsAndFlights();
      FlightDto[]  outboundFlights  =
                      findTwoOutboundFlightsFromOneAirport();
      //  Exercise  System
      List  flightsAtOrigin  =  facade.getFlightsByOriginAirport(
                            outboundFlights[0].getOriginAirportId());
      //  Verify  Outcome
      assertExactly2FlightsInDtoList(  "Flights  at  origin",
                                                   outboundFlights,
                                                   flightsAtOrigin);
}

To make the use of a Standard Fixture really obvious, this example shows a Fresh Fixture that is created explicitly in each test by calling the same Creation Method to set up the Standard Fixture (i.e., using Delegated Setup ). We could have achieved the same effect by putting the fixture construction logic into the setUp method, thus using Implicit Setup . The resulting test would look identical to one that uses a Shared Fixture .

Fresh Fixture

Also known as

Fresh Context, Private Fixture

Which fixture strategy should we use?

Each test constructs its own brand-new test fixture for its own private use.

image

Every test needs a test fixture. It defines the state of the test environment before the test. The choice of whether to build the fixture from scratch each time the test is run or to reuse a fixture built earlier is a key test automation decision.

When each test creates a Fresh Fixture , Erratic Tests (page 228 ) are less likely and the testing effort is more likely to result in Tests as Documentation (see page 23 ).

How It Works

We design and build the test fixture such that only a single run of a single test will use it. We construct the fixture as part of running the test and tear down the fixture when the test has finished. We do not reuse any fixture left over by other tests or other test runs. This way, we start and end every test with a "clean slate."

When to Use It

We should use a Fresh Fixture whenever we want to avoid any interdependencies between tests that can result in Erratic Tests such as Lonely Tests (see Erratic Test ) or Interacting Tests (see Erratic Test ). If we cannot use a Fresh Fixture because it slows the tests down too much, we should consider using an Immutable Shared Fixture (see Shared Fixture on page 317 ) before resorting to a Shared Fixture . Note that using a Database Partitioning Scheme (see Database Sandbox on page 650 ) to create a private Database Sandbox for the test that no other tests will touch does not result in a Fresh Fixture because subsequent test runs could use the same fixture.

Implementation Notes

A fixture is considered a Fresh Fixture if we intend to use it a single time. Whether the Fresh Fixture is transient or persistent depends on the nature of the SUT and how the tests are written ( Figure 18.3 ). While the intent is the same, the implementation considerations are somewhat different when the Fresh Fixture is persistent. Fixture setup is largely unaffected, so it is discussed as a feature common to all such fixtures. Fixture teardown is specific to the particular variation.

Figure 18.3. Test fixture strategies. A fixture can be either Fresh, Shared, or a combination of the two (the immutable Shared Fixture) based on whether some, or all, of it persists between tests.

image

Why Does a Fixture Persist?

The fixture we construct may hang around after the Test Method (page 348 ) has finished executing for one of two reasons. First, if the fixture primarily consists of the state of some other objects or components on which the SUT depends, its persistence is determined by whether those other objects are themselves persistent. A database is one such beast. That's because as soon as some code persists the fixture objects into a database, the objects "hang around" long after our test is done. Their existence in the database opens the door to collisions between multiple runs of our own test ( Unrepeatable Test ; see Erratic Test ). Other tests may also be able to access those objects, which can result in other forms of Erratic Tests such as Interacting Tests and Test Run Wars . If we must use a database or other form of object persistence, we should take extra steps to keep the fixture private. In addition, we should tear down the fixture after each Test Method .

The second reason that a fixture might persist lies within the control of our tests—namely, which kind of variable we choose to hold the reference to the fixture. Local variables naturally go out of scope when the Test Method finishes executing; therefore any fixture held in a local variable will be destroyed by garbage collection. Instance variables go out of scope when the Testcase Object is destroyed 8 and require explicit teardown only if the xUnit framework doesn't recreate the Testcase Object s during each test run. By contrast, class variables usually result in persistent fixtures that can outlive a single test method or even a test run and should therefore be avoided when using a Fresh Fixture .

In practice, our fixture will not normally be persistent in unit tests 9 unless we have tightly coupled our application logic to the database. A fixture is more likely to be persistent when we are writing customer tests or possibly component tests .

Fresh Fixture Setup

Construction of the fixture is largely unaffected by whether it is persistent or transient. The primary consideration is the location of the code to set up the fixture. We can use In-line Setup (page 408 ) if the fixture setup is relatively simple. For more complex fixtures, we generally prefer using Delegated Setup (page 411 ) when our Test Methods are organized using Testcase Class per Class (page 617 ) or Testcase Class per Feature (page 624 ). We can use Implicit Setup (page 424 ) to build the fixture if we have used the Testcase Class per Fixture (page 631 ) organization.

Variation: Transient Fresh Fixture

If we need to refer to the fixture from several places in the test, we should use only local variables or instance variables to refer to the fixture. In most cases we can depend on Garbage-Collected Teardown (page 500 ) to destroy the fixture without any effort on our part.

Note that a Standard Fixture (page 305 ) can also be a Fresh Fixture if the fixture is built from scratch before each Test Method is run. This approach reuses the design of the fixture rather than the instance . It is commonly encountered when we use Implicit Setup but we are not using Testcase Class per Fixture to organize our Test Methods .

Variation: Persistent Fresh Fixture

If we do end up using a Persistent Fresh Fixture , either we need to tear down the fixture or we need to take special measures to avoid the need for its teardown. We can tear down the fixture using In-line Teardown (page 509 ), Implicit Teardown (page 516 ), Delegated Teardown (see In-line Teardown ) , or Automated Teardown (page 503 ) to leave the test environment in the same state as when we entered it.

To avoid fixture teardown, we can use a Distinct Generated Value (see Generated Value on page 723 ) for each fixture object that must be unique. This strategy can become the basis of a Database Partitioning Scheme that seeks to isolate the tests and test runners from one another. It would prevent Resource Leakage (see Erratic Test ) in case our teardown process fails. We can also combine this approach with one of the teardown patterns to be doubly sure that no Unrepeatable Tests or Interacting Tests exist.

Not surprisingly, this additional work has some drawbacks: It makes tests more complicated to write and it often leads to Slow Tests (page 253 ). A natural reaction is to take advantage of the persistence of the fixture by reusing it across many tests, thereby avoiding the overhead of setting it up and tearing it down. Unfortunately, this choice has many undesirable ramifications because it violates one of our major principles: Keep Tests Independent (see page 42 ). The resulting Shared Fixture invariably leads to Interacting Tests and Unrepeatable Tests , if not immediately, then at some point down the road. We should not venture down this road without fully understanding the consequences!

Motivating Example

Here's an example of a Shared Fixture :

static  Flight  flight;
public  void  setUp()  {
      if  (flight  ==  null)  {    //  Lazy  SetUp
          Airport  departAirport  =  new  Airport("Calgary",  "YYC");
          Airport  destAirport  =  new  Airport("Toronto",  "YYZ");
          flight  =  new  Flight(  flightNumber,
                                          departAirport,
                                          destAirport);
      }
}

public  void  testGetStatus_inital_S()  {
      //  implicit  setup
      //  exercise  SUT  and  verify  outcome
      assertEquals(FlightState.PROPOSED,  flight.getStatus());
      //  teardown
}
public  void  testGetStatus_cancelled()  {
      //  implicit  setup  partially  overridden
      flight.cancel();
      //  exercise  SUT  and  verify  outcome
      assertEquals(FlightState.CANCELLED,  flight.getStatus());
      //  teardown
}

Based on the code that actually sets up the fixture as shown here, it is a normal Shared Fixture, but we could have just as easily used a Prebuilt Fixture (page 429 ) for this motivating example. Either way, these tests could start interacting at any time.

Refactoring Notes

Suppose we are using a Shared Fixture (same design, single copy) and decide to refactor it to use a Fresh Fixture . We can start by refactoring the test to use a fresh Standard Fixture (same design, many copies). Then we can decide whether we want to further evolve the test so that it builds a Minimal Fixture (page 302 ) by pruning the fixture setup logic to the bare minimum using a Minimize Data (page 738 ) refactoring. This point would also be good time to group Test Methods that need the same type of test fixture into a Testcase Class per Fixture and use Implicit Setup ; this use of a Standard Fixture would reduce the number of Minimal Fixtures we need to design and build.

Example: Fresh Fixture

Here's the same test converted to a Fresh Fixture to avoid any possibility of Interacting Tests :

public  void  testGetStatus_inital()  {
        //  setup
      Flight  flight  =  createAnonymousFlight();
      //  exercise  SUT  and  verify  outcome
      assertEquals(FlightState.PROPOSED,  flight.getStatus());
      //  teardown
      //        garbage-collected
}

public  void  testGetStatus_cancelled2()  {
      //  setup
      Flight  flight  =  createAnonymousCancelledFlight();
      //  exercise  SUT  and  verify  outcome
      assertEquals(FlightState.CANCELLED,  flight.getStatus());
      //  teardown
      //        garbage-collected
}

Note the use of Anonymous Creation Methods (see Creation Method on page 415 ) to construct the appropriate state Flight object in each test.

Shared Fixture

Also known as

Shared Context, Leftover Fixture, Reused Fixture, Stale Fixture

How can we avoid Slow Tests?

Which fixture strategy should we use?

We reuse the same instance of the test fixture across many tests.

image

To execute an automated test, we require a text fixture that is well understood and completely deterministic. Setting up a Fresh Fixture (page 311 ) can be time-consuming, especially when we are dealing with complex system state stored in a test database.

We can make our tests run faster by reusing the same fixture for several or many tests.

How It Works

The basic concept is pretty simple: We create a Standard Fixture (page 305 ) fixture that outlasts the lifetime of a single Testcase Object (page 382 ). This approach allows multiple tests to reuse the same test fixture without destroying that fixture and recreating it between tests. A Shared Fixture can be either a Prebuilt Fixture that is reused by one or more tests in many test runs or a fixture that is created by one test and reused by another test within the same test run. In either case, the key consideration is that many tests do not create their own fixtures but rather reuse a fixture "left over" from some other activity. The tests run faster because they have less fixture setup to perform, which may result in the test automater having to do less work to define the fixture for each test.

When to Use It

Regardless of why we use them, Shared Fixtures come with some baggage that we should understand before we head down this path. The major issue with a Shared Fixture is that it can lead to interactions between tests, possibly resulting in Erratic Tests (page 228 ) if some tests depend on the outcomes of other tests. Another potential problem is that a fixture designed to serve many tests is bound to be much more complicated than the Minimal Fixture (page 302 ) needed for a single test. This greater complexity will typically take more effort to design and can lead to a Fragile Fixture (see Fragile Test on page 239 ) later on down the road when we need to modify the fixture.

A Shared Fixture will often result in an Obscure Test (page 186 ) because the fixture is not constructed inside the test. This potential disadvantage can be mitigated by using Finder Methods (see Test Utility Method on page 599 ) with Intent-Revealing Names [SBPP] to access the relevant parts of the fixture.

There are some valid reasons for using a Shared Fixture and some misguided ones. Many of the variations have been devised primarily to mitigate the negative consequences of using a Shared Fixture . So, what are good reasons for using a Shared Fixture ?

Variation: Slow Tests

We can use a Shared Fixture when we cannot afford to build a new Fresh Fixture for each test. Typically, this scenario will occur when it takes too much processing to build a new fixture for each test, which often leads to Slow Tests (page 253 ). It most commonly occurs when we are testing with real test databases due to the high cost of creating each of the records. This growth in overhead tends to be exacerbated when we use the API of the SUT to create the reference data, because the SUT often does a lot of input validation, which may involve reading some of the just-written records.

A better solution is to make the tests run faster by not interacting with the database at all. For a more complete list of options, see the solutions to Slow Tests and the sidebar " Faster Tests Without Shared Fixtures " (page 319 ).


Faster Tests Without Shared Fixtures

The first reaction to Slow Tests (page 253 ) is often to switch to a Shared Fixture (page 317 ) approach. Several other solutions are available, however. This sidebar describes some experiences on several projects.

Fake Database

On one of our early XP projects, we wrote a lot of tests that accessed the database. At first we used a Shared Fixture. When we encountered Interacting Tests (see Erratic Test on page 228 ) and later Test Run Wars (see Erratic Test ), however, we changed to a Fresh Fixture (page 311 ) approach. Because these tests needed a fair bit of reference data, they were taking a long time to run. On average, for every read or write the SUT did to or from the database, each test did several more. It was taking 15 minutes to run the full test suite of several hundred tests, which greatly impeded our ability to integrate our work quickly and often.

At the time, we were using a data access layer to keep the SQL out of our code. We soon discovered that it allowed us to replace the real database with a functionally equivalent Fake Database (see Fake Object on page 551 ). We started out by using simple HashTable s to store the objects against a key. This approach allowed us to run many of our simpler tests "in memory" rather than against the database. And that bought us a significant drop in test execution time.

Our persistence framework supported an object query interface. We were able to build an interpreter of the object queries that ran against our HashTable database implementation and that allowed the majority of our tests to work entirely in memory. On average, our tests ran about 50 times faster in memory than with the database. For example, a test suite that took 10 minutes to run with the database took 10 seconds to run in memory.

This approach was so successful that we have reused the same testing infrastructure on many of our subsequent projects. Using the faked-out persistence framework also means we don't have to bother with building a "real database" until our object models stabilize, which can be several months into the project.

Incremental Speedups

Ted O'Grady and Joseph King are agile team leads on a large (50-plus developers, subject matter experts, and testers) eXtreme Programming project. Like many project teams building database-centric applications, they suffered from Slow Tests . But they found a way around this problem: As of late 2005, their check-in test suite ran in less than 8 minutes compared to 8 hours for a full test run against the database. That is a pretty impressive speed difference. Here is their story:

Currently we have about 6,700 tests that we run on a regular basis. We've actually tried a few things to speed up the tests and they've evolved over time.
In January 2004, we were running our tests directly against a database via Toplink.
In June 2004, we modified the application so we could run tests against an in-memory, in-process Java database (HSQL). This cut the time to run in half.
In August 2004, we created a test-only framework that allowed Toplink to work without a database at all. That cut the time to run all the tests by a factor of 10.
In July 2005, we built a shared "check-in" test execution server that allowed us to run tests remotely. This didn't save any time at first but it has proven to be quite useful nonetheless.
In July 2005, we also started using a clustering framework that allowed us to run tests distributed across a network. This cut the time to run the tests in half.
In August 2005, we removed the GUI and Master Data (reference data crud) tests from the "check-in suite" and ran them only from Cruise Control. This cut the time to run by approximately 15% to 20%.

Since May 2004, we have also had Cruise Control run all the tests against the database at regular intervals. The time it takes Cruise Control to complete [the build and run the tests] has grown with the number of tests from an hour to nearly 8 hours now.
When a threshold has been met that prevents the developers from (a) running [the tests] frequently when developing and (b) creating long check-in queues as people wait for the token to check in, we have adapted by experimenting with new techniques. As a rule we try to keep the running of the tests under 5 minutes, with anything over 8 minutes being a trigger to try something new.
We have resisted thus far the temptation to run only a subset of the tests and instead focused on ways to speed up running all the tests—although as you can see, we have begun removing the tests developers must run continuously (e.g., Master Data and GUI test suites are not required to check in, as they are run by Cruise Control and are areas that change infrequently).
Two of the most interesting solutions recently (aside from the in-memory framework) are the test server and the clustering framework.

The test server (named the "check-in" box here) is actually quite useful and has proven to be reliable and robust. We bought an Opteron box that is roughly twice as fast as the development boxes (really, the fastest box we could find). The server has an account set up for each development machine in the pit. Using the UNIX tool rsynch, the Eclipse workspace is synchronized with the user's corresponding server account file system. A series of shell scripts then recreates the database on the server for the remote account and runs all the development tests. When the tests have completed, a list of times to run each test is dumped to the console, along with a MyTestSuite.java class containing all the test failures, which the developer can use to run locally to fix any tests that have broken. The biggest advantage the remote server has provided is that it makes running a large number of tests feel fast again, because the developer can continue working while he or she waits for the results of the test server to come back.
The clustering framework (based on Condor) was quite fast but had the defect that it had to ship the entire workspace (11MB) to all the nodes on the network (×20), which had a significant cost, especially when a dozen pairs are using it. In comparison, the test server uses rsynch, which copies only the files that are new or different in the developer's workspace. The clustering framework also proved to be less reliable than the server solution, frequently not returning any status of the test run. There were also some tests that would not run reliably on the framework. Since it gave us roughly the same performance as the "check-in" test server, we have put this solution on the back burner.

Further Reading

A more detailed description of the first experience can be found at http://FasterTestsPaper.gerardmeszaros.com .


Variation: Incremental Tests

We may also use Shared Fixtures when we have a long, complex sequence of actions, each of which depends on the previous actions. In customer tests, this may show up as a work flow; in unit tests, it may be a sequence of method calls on the same object. This case might be tested using a single Eager Test (see Assertion Roulette on page 224 ). The alternative is to put each distinct action into a separate Test Method (page 348 ) that builds upon the actions of a previous test operating on a Shared Fixture . This approach, which is an example of Chained Tests (page 454 ), is how testers in the "testing" (i.e., QA) community often operate: They set up a fixture and then run a sequence of tests, each of which builds upon the fixture. The testers do have one significant advantage over our Fully Automated Tests (see page 26 ): When a test partway through the chain fails, they are available to make decisions about how to recover or whether it is worth proceeding at all. In contrast, our automated tests just keep running, and many of them will generate test failures or errors because they did not find the fixture as expected and, therefore, the SUT behaved (probably correctly) differently. The resulting test results can obscure the real cause of the failure in a sea of red. With some experience it is often possible to recognize the failure pattern and deduce the root cause. 10

This troubleshooting can be made simpler by starting each Test Method with one or more Guard Assertions (page 490 ) that document the assumptions the Test Method makes about the state of the fixture. When these assertions fail, they tell us to look elsewhere—either at tests that failed earlier in the test suite or at the order in which the tests were run.

Implementation Notes

A key implementation question with Shared Fixtures is, How do tests know about the objects in the Shared Fixture so they can (re)use them? Because the point of a Shared Fixture is to save execution time and effort by having multiple tests use the same instance of the test fixture, we'll need to keep a reference to the fixture we create. That way, we can find the fixture if it already exists and we can inform other tests that it now exists once we have constructed it. We have more choices available to us with Per-Run Fixtures because we can "remember" the fixture we set up in code more easily than a Prebuilt Fixture (page 429 ) set up by a different program. Although we could just hard-code the identifiers (e.g., database keys) of the fixture objects into all our tests, that technique would result in a Fragile Fixture . To avoid this problem, we need to keep a reference to the fixture when we create it and we need to make it possible for all tests to access that reference.

Variation: Per-Run Fixture

The simplest form of Shared Fixture is the Per-Run Fixture , in which we set up the fixture at the beginning of a test run and allow it to be shared by the tests within the run. Ideally, the fixture won't outlive the test run and we don't have to worry about interactions between test runs such as Unrepeatable Tests (a cause of Erratic Tests ). If the fixture is persistent, such as when it is stored in a database, we may need to do explicit fixture teardown.

If a Per-Run Fixture is shared only within a single Testcase Class (page 373 ), the simplest solution is to use a class variable for each fixture object we need to hold a reference to and then use either Lazy Setup (page 435 ) or Suite Fixture Setup (page 441 ) to initialize the objects just before we run the first test in the suite. If we want to share the test fixture between many Testcase Classes, we'll need to use a Setup Decorator (page 447 ) to hold the setUp and tearDown methods and a Test Fixture Registry (see Test Helper on page 643 ) (which could just be the test database) to access the fixture.

Variation: Immutable Shared Fixture

The problem with Shared Fixtures is that they lead to Erratic Tests if tests modify the Shared Fixture (page 317 ). Shared Fixtures violate the Independent Test principle (see page 42 ). We can avoid this problem by making the Shared Fixture immutable; that is, we partition the fixture needed by tests into two logical parts. The first part is the stuff every test needs to have present but is never modified by any tests—that is, the Immutable Shared Fixture . The second part is the objects that any test needs to modify or delete; these objects should be built by each test as Fresh Fixtures .

The most difficult part of applying an Immutable Shared Fixture is deciding what constitutes a change to an object. The key guideline is this: If any test perceives something done by another test as a change to an object in the Immutable Shared Fixture , then that change shouldn't be allowed in any test with which it shares the fixture. Most commonly, the Immutable Shared Fixture consists of reference data that is needed by the actual per-test fixtures. The per-test fixtures can then be built as Fresh Fixtures on top of the Immutable Shared Fixture .

Motivating Example

The following example shows a Testcase Class setting up the test fixture via Implicit Setup (page 424 ). Each Test Method uses an instance variable to access the contents of the fixture.

public  void  testGetFlightsByFromAirport_OneOutboundFlight()
                  throws  Exception  {
      setupStandardAirportsAndFlights();
      FlightDto  outboundFlight  =  findOneOutboundFlight();
      //  Exercise  System
      List  flightsAtOrigin  =  facade.getFlightsByOriginAirport(
                                outboundFlight.getOriginAirportId());
      //  Verify  Outcome
      assertOnly1FlightInDtoList(  "Flights  at  origin",
                                                 outboundFlight,
                                                 flightsAtOrigin);
}

public  void  testGetFlightsByFromAirport_TwoOutboundFlights()
                  throws  Exception  {
      setupStandardAirportsAndFlights();
      FlightDto[]  outboundFlights  =
                          findTwoOutboundFlightsFromOneAirport();
      //  Exercise  System
      List  flightsAtOrigin  =  facade.getFlightsByOriginAirport(
                                      outboundFlights[0].getOriginAirportId());
      //  Verify  Outcome
      assertExactly2FlightsInDtoList(  "Flights  at  origin",
                                                       outboundFlights,
                                                       flightsAtOrigin);
}

Note that the setUp method is run once for each Test Method . If the fixture setup is fairly complex and involves accessing a database, this approach could result in Slow Tests .

Refactoring Notes

To convert a Testcase Class from a Standard Fixture to a Shared Fixture , we simply convert the instance variables into class variables to make the fixture outlast the creating Testcase Object . We then need to initialize the class variables just once to avoid recreating them for each Test Method ; Lazy Setup is an easy way to accomplish this task. Of course, other ways to set up the Shared Fixture are also possible, such as Setup Decorator or Suite Fixture Setup .

Example: Shared Fixture

This example shows the fixture converted to a Shared Fixture set up using Lazy Setup .

protected  void  setUp()  throws  Exception  {
      if  (sharedFixtureInitialized)  {
          return;
          }
          facade  =  new  FlightMgmtFacadeImpl();
          setupStandardAirportsAndFlights();
          sharedFixtureInitialized  =  true;
}

protected  void  tearDown()  throws  Exception  {
          //  We  cannot  delete  any  objects  because  we  don't  know
          //  whether  this  is  the  last  test
}

The Lazy Initialization [SBPP] logic in the setUp method ensures that the Shared Fixture is created whenever the class variable is uninitialized. The Test Methods have also been modified to use a Finder Method to access the contents of the fixture:

public  void  testGetFlightsByFromAirport_OneOutboundFlight()
               throws  Exception  {
      FlightDto  outboundFlight  =  findOneOutboundFlight();
      //  Exercise  System
      List  flightsAtOrigin  =  facade.getFlightsByOriginAirport(
                                       outboundFlight.getOriginAirportId());
      //  Verify  Outcome
      assertOnly1FlightInDtoList(  "Flights  at  origin",
                                                 outboundFlight,
                                                 flightsAtOrigin);
}

public  void  testGetFlightsByFromAirport_TwoOutboundFlights()
               throws  Exception  {
      FlightDto[]  outboundFlights  =
            findTwoOutboundFlightsFromOneAirport();
      //  Exercise  System
      List  flightsAtOrigin  =  facade.getFlightsByOriginAirport(
                              outboundFlights[0].getOriginAirportId());
      //  Verify  Outcome
      assertExactly2FlightsInDtoList(  "Flights  at  origin",
                                                       outboundFlights,
                                                       flightsAtOrigin);
}

Example: Immutable Shared Fixture

Here's an example of Shared Fixture "pollution":

public  void  testCancel_proposed_p()throws  Exception  {
    //  shared  fixture
    BigDecimal  proposedFlightId  =  findProposedFlight();
    //            exercise  SUT
    facade.cancelFlight(proposedFlightId);
    //  verify  outcome
    try{
        assertEquals(FlightState.CANCELLED,
                            facade.findFlightById(proposedFlightId));
    }  finally  {
         //  teardown
         //  try  to  undo  the  damage;  hope  this  works!
         facade.overrideStatus(  proposedFlightId,
                                            FlightState.PROPOSED);
    }
}

We can avoid this problem by making the Shared Fixture immutable; that is, we partition the fixture needed by tests into two logical parts. The first part is the stuff every test needs to have present but is never modified by any tests—that is, the Immutable Shared Fixture . The second part is the objects that any test needs to modify or delete; these objects should be built by each test as Fresh Fixtures .

Here's the same test modified to use an Immutable Shared Fixture . We simply created our own mutableFlight within the test.

public  void  testCancel_proposed()  throws  Exception  {
    //  fixture  setup
    BigDecimal  mutableFlightId  =
          createFlightBetweenInsigificantAirports();
    //  exercise  SUT
    facade.cancelFlight(mutableFlightId);
    //  verify  outcome
    assertEquals(  FlightState.CANCELLED,
                         facade.findFlightById(mutableFlightId));
    //  teardown
    //     None  required  because  we  let  the  SUT  create
    //     new  IDs  for  each  flight.  We  might  need  to  clean  out
    //     the  database  eventually.
}

Note that we don't need any fixture teardown logic in this version of the test because the SUT uses a Distinct Generated Value (see Generated Value on page 723 )—that is, we do not supply a flight number. We also use the predefined dummyAirport1 and dummyAirport2 to avoid changing the number of flights for airports used by other tests. Therefore, the mutable flights can accumulate in the database trouble-free.

Back Door Manipulation

Also known as

Layer-Crossing Test

How can we verify logic independently when we cannot use a round-trip test?

We set up the test fixture or verify the outcome by going through a back door (such as direct database access).

image

Every test requires a starting point (the test fixture) and an expected finishing point (the expected results). The "normal" approach is to set up the fixture and verify the outcome by using the API of the SUT itself. In some circumstances this is either not possible or not desirable.

In some situations we can use Back Door Manipulation to set up the fixture and/or verify the SUT's state.

How It Works

The state of the SUT comes in many flavors. It can be stored in memory, on disk as files, in a database, or in other applications with which the SUT interacts. Whatever form it takes, the pre-conditions of a test typically require that the state of the SUT is not just known but is a specific state. Likewise, at the end of the test we often want to do State Verification (page 462 ) of the SUT's state.

If we have access to the state of the SUT from outside the SUT, the test can set up the pre-test state of the SUT by bypassing the normal API of the SUT and interacting directly with whatever is holding that state via a "back door." When exercising of the SUT has been completed, the test can similarly access the post-test state of the SUT via a back door to compare it with expected outcome. For customer tests, the back door is most commonly a test database, but it could also be some other component on which the SUT depends, including a Registry [PEAA] object or even the file system. For unit tests, the back door is some other class or object or an alternative interface of the SUT (or a Test-Specific Subclass ; page 579 ) that exposes the state in a way "normal" clients wouldn't use. We can also replace a depended-on component (DOC) with a suitably configured Test Double (page 522 ) instead of using the real thing if that makes the job easier.

When to Use It

We might choose to use Back Door Manipulation for several reasons which we'll examine in more detail shortly. A prerequisite for using this technique is that some sort of back door to the state of the system must exist. The main drawback of Back Door Manipulation is that our tests—or the Test Utility Methods (page 599 ) they call—become much more closely coupled to the design decisions we make about how to represent the state of the SUT. If we need to change those decisions, we may encounter Fragile Tests (page 239 ). We need to decide whether this price is acceptable on a case-by-case basis. We can greatly reduce the impact of the close coupling by encapsulating all Back Door Manipulation in Test Utility Methods .

Using Back Door Manipulation can also lead to Obscure Tests (page 186 ) by hiding the relationship of the test outcome to the test fixture. We can avoid this problem by including the test data being passed to the Back Door Manipulation mechanism within the Testcase Class (page 373 ), or at least mitigate it by using Finder Methods (see Test Utility Method ) to refer to the objects in the fixture via intent-revealing names.

A common application of Back Door Manipulation involves testing basic CRUD (Create, Read, Update, Delete) operations on the SUT's state. In such a case, we want to verify that the information persisted and can be recovered in the same form. It is difficult to write round-trip tests for "Read" without also testing "Create"; likewise, it is difficult to test "Update" or "Delete" without testing both "Create" and "Read." We can certainly test these operations by using round-trip tests, but this kind of testing won't detect certain types of systemic problems, such as putting information into the wrong database column. One solution is to conduct layer-crossing tests that use Back Door Manipulation to set up or verify the contents of the database directly. For a "Read" test, the test sets up the contents of the database using Back Door Setup and then asks the SUT to read the data. For a "Write" test, the test asks the system to write certain objects and then uses Back Door Verification on the contents of the database.

Variation: Back Door Setup

One reason for doing Back Door Manipulation is to make tests run faster. If a system does a lot of processing before putting data into its data store, the time it takes for a test to set up the fixture via the SUT's API could be quite significant. One way to make the tests run faster is to determine what those data stores should look like and then create a means to set them up via the back door rather than through the API. Unfortunately, this technique introduces its own problem: Because Back Door Setup bypasses enforcement of the object creation business rules, we may find ourselves creating fixtures that are not realistic and possibly even invalid. This problem may creep in over time as the business rules are modified in response to changing business needs. At the same time, this approach may allow us to create test scenarios that the SUT will not let us set up through its API.

When we share a database between our SUT and another application, we need to verify that we are using the database correctly and that we can handle all possible data configurations the other applications might create. Back Door Setup is a good way to establish these configurations—and it may be the only way if the SUT either doesn't write those tables or writes only specific (and valid) data configurations. Back Door Setup lets us create those "impossible" configurations easily so we can verify how the SUT behaves in these situations.

Variation: Back Door Verification

Back Door Verification involves sneaking in to do State Verification of the SUT's post-exercise state via a back door; it is mostly applicable to customer tests (or functional tests, as they are sometimes called). The back door is typically an alternative way to examine the objects in the database, usually through a standard API such as SQL or via data exports that can then be examined with a file comparison utility program.

As mentioned earlier, Back Door Manipulation can make tests run faster. If the only way to get at the SUT's state is to invoke an expensive operation (such as a complex report) or an operation that further modifies the SUT's state, we may be better off using Back Door Manipulation .

Another reason for doing Back Door Manipulation is that other systems expect the SUT to store its state in a specific way, which they can then access directly. This is a form of indirect output. In this situation, standard round-trip tests cannot prove that the SUT's behavior is correct because they cannot detect a systematic problem if the "Write" and "Read" operations make the same mistake, such as putting information into the wrong database column. The solution is a layer-crossing test that looks at the contents of the database directly to verify that the information is stored correctly. For a "Write" test, the test asks the system to write certain objects and then inspects the contents of the database via the back door.

Variation: Back Door Teardown

We can also use Back Door Manipulation to tear down a Fresh Fixture (page 311 ) that is stored in a test database. This ability is especially beneficial if we can use bulk database commands to wipe clean whole tables, as in Table Truncation Teardown (page 661 ) or Transaction Rollback Teardown (page 668 ).

Implementation Notes

How we implement Back Door Manipulation depends on where the fixture lives and how easily we can access the state of the SUT. It also depends on why we are doing Back Door Manipulation . This section lists the most common implementations, but feel free to use your imagination and come up with other ways to use this pattern.

Variation: Database Population Script

When the SUT stores its state in a database that it accesses as it runs, the easiest way to do Back Door Manipulation is to load data directly into that database before invoking the SUT. This approach is most commonly required when we are writing customer tests, but it may also be required for unit tests if the classes we are testing interact directly with the database. We must first determine the pre-conditions of the test and, from that information, identify the data that the test requires for its fixture. We then define a database script that inserts the corresponding records directly into the database bypassing the SUT logic. We use this Database Population Script whenever we want to set up the test fixture—a decision that depends on which test fixture strategy we have chosen. (See Chapter 6 , Test Automation Strategy, for more on that topic.)

When deciding to use a Database Population Script , we will need to maintain both the Database Population Script and the files it takes as input whenever we modify either the structure of the SUT's data stores or the semantics of the data in them. This requirement can increase the maintenance cost of the tests.

Variation: Data Loader

A Data Loader is a special program that loads data into the SUT's data store. It differs from a Database Population Script in that the Data Loader is written in a programming language rather than a database language. This gives us a bit more flexibility and allows us to use the Data Loader even when the system state is stored somewhere other than a relational database.

If the data store is external to the SUT, such as in a relational database, the Data Loader can be "just another application" that writes to that data store. It would use the database in much the same way as the SUT but would get its inputs from a file rather than from wherever the SUT normally gets its inputs (e.g., other "upstream" programs). When we are using an object relational mapping (ORM) tool to access the database from our SUT, a simple way to build the Data Loader is to use the same domain objects and mappings in our Data Loader . We just create the desired objects in memory and commit the ORM's unit of work to save them into the database.

If the SUT stores data in internal data structures (e.g., in memory), the Data Loader may need to be an interface provided by the SUT itself. The following characteristics differentiate it from the normal functionality provided by the SUT:

  • It is used only by the tests.
  • It reads the data from a file rather than wherever the SUT normally gets the data.
  • It bypasses a lot of the "edit checks" (input validation) normally done by the SUT.

The input files may be simple flat files containing comma- or tab-delimited text, or they could be structured using XML. DbUnit is an extension of JUnit that implements Data Loader for fixture setup.

Variation: Database Extraction Script

When the SUT stores its state in a database that it accesses as it runs, we can take advantage of this structure to do Back Door Verification . We simply use a database script to extract data from the test database and verify that it contains the right data either by comparing it to previously prepared "extract" files or by ensuring that specific queries return the right number of records.

Variation: Data Retriever

A Data Retriever is the analog of a Data Loader that retrieves the state from the SUT when doing Back Door Verification . Like a trusty dog, it "fetches" the data so that we can compare it with our expected results within our tests. DbUnit is an extension of JUnit that implements Data Retriever to support result verification.

Variation: Test Double as Back Door

So far, all of the implementation techniques described here have involved interacting with a DOC of the SUT to set up or tear down the fixture or to verify the expected outcome. Probably the most common form of Back Door Manipulation involves replacing the DOC with a Test Double . One option is to use a Fake Object (page 551 ) that we have preloaded with some data as though the SUT had already been interacting with it; this strategy allows us to avoid using the SUT to set up the SUT's state. The other option is to use some kind of Configurable Test Double (page 558 ), such as a Mock Object (page 544 ) or a Test Stub (page 529 ). Either way, we can completely avoid Obscure Tests by making the state of the Test Double visible within the Test Method (page 348 ).

When we want to perform Behavior Verification (page 468 ) of the calls made by the SUT to one or more DOCs, we can use a layer-crossing test that replaces the DOC with a Test Spy (page 538 ) or a Mock Object . When we want to verify that the SUT behaves a specific way when it receives indirect inputs from a DOC (or when in some specific external state), we can replace the DOC with a Test Stub .

Motivating Example

The following round-trip test verifies the basic functionality of removing a flight by interacting with the SUT only via the front door. But it does not verify the indirect outputs of the SUT—namely, that the SUT is expected to call a logger to log each time a flight is removed along with the day/time when the request was made and the user ID of the requester. In many systems, this would be an example of "layer-crossing behavior": The logger is part of a generic infrastructure layer, while the SUT is an application-specific behavior.

public  void  testRemoveFlight()  throws  Exception  {
    //  setup
    FlightDto  expectedFlightDto  =  createARegisteredFlight();
    FlightManagementFacade  facade  =  new  FlightManagementFacadeImpl();
    //  exercise
    facade.removeFlight(expectedFlightDto.getFlightNumber());
    //  verify
    assertFalse("flight  should  not  exist  after  being  removed",
                      facade.flightExists(  expectedFlightDto.
                                                               getFlightNumber()));
}

Refactoring Notes

We can convert this test to use Back Door Verification by adding result verification code to access and verify the logger's state. We can do so either by reading that state from the logger's database or by replacing the logger with a Test Spy that saves the state for easy access by the tests.

Example: Back Door Result Verification Using a Test Spy

Here's the same test converted to use a Test Spy to access the post-test state of the logger:

public  void  testRemoveFlightLogging_recordingTestStub()
             throws  Exception  {
      //  fixture  setup
      FlightDto  expectedFlightDto  =  createAnUnregFlight();
      FlightManagementFacade  facade  =
              new  FlightManagementFacadeImpl();
      //      Test  Double  setup
      AuditLogSpy  logSpy  =  new  AuditLogSpy();
      facade.setAuditLog(logSpy);
      //  exercise
      facade.removeFlight(expectedFlightDto.getFlightNumber());
      //  verify
      assertEquals("number  of  calls",  1,
                          logSpy.getNumberOfCalls());
      assertEquals("action  code",
                          Helper.REMOVE_FLIGHT_ACTION_CODE,
                          logSpy.getActionCode());
      assertEquals("date",  helper.getTodaysDateWithoutTime(),
                          logSpy.getDate());
      assertEquals("user",  Helper.TEST_USER_NAME,
                          logSpy.getUser());
      assertEquals("detail",
                          expectedFlightDto.getFlightNumber(),
                          logSpy.getDetail());
}

This approach would be the better way to verify the logging if the logger's database contained so many entries that it wasn't practical to verify the new entries using Delta Assertions (page 485 ).

Example: Back Door Fixture Setup

The next example shows how we can set up a fixture using the database as a back door to the SUT. The test inserts a record into the EmailSubscription table and then asks the SUT to find it. It then makes assertions on various fields of the object returned by the SUT to verify that the record was read correctly.

static  final  String          TABLE_NAME  =  "EmailSubscription";
static  final  BigDecimal  RECORD_ID    =  new  BigDecimal("111");

static  final  String  LOGIN_ID  =  "Bob";
static  final  String  EMAIL_ID  =  "[email protected]";

public  void  setUp()  throws  Exception  {
   String  xmlString  =
             "<?xml  version='1.0'  encoding='UTF-8'?>"  +
             "<dataset>"  +
             "        <"  +  TABLE_NAME  +
             "                EmailSubscriptionId='"  +  RECORD_ID  +  "'"  +
             "                UserLoginId='"  +  LOGIN_ID  +  "'"  +
             "                EmailAddress='"  +  EMAIL_ID  +  "'"  +
             "                RecordVersionNum='62'  "  +
             "                CreateByUserId='MappingTest'  "  +
             "                CreateDateTime='2004-03-01  00:00:00.0'    "  +
             "                LastModByUserId='MappingTest'  "  +
             "                LastModDateTime='2004-03-01  00:00:00.0'/>"  +
             "</dataset>";
    insertRowsIntoDatabase(xmlString);
}

public  void  testRead_Login()  throws  Exception  {
    //  exercise
    EmailSubscription  subs  =
            EmailSubscription.findInstanceWithId(RECORD_ID);
    //  verify
    assertNotNull("Email  Subscription",  subs);
    assertEquals("User  Name",  LOGIN_ID,  subs.getUserName());
}

public  void  testRead_Email()  throws  Exception  {
    //  exercise
    EmailSubscription  subs  =
                EmailSubscription.findInstanceWithId(RECORD_ID);
    //  verify
    assertNotNull("Email  Subscription",  subs);
    assertEquals("Email  Address",
                              EMAIL_ID,
                              subs.getEmailAddress());
}

The XML document used to populate the database is built within the Testcase Class so as to avoid the Mystery Guest (see Obscure Test ) that would have been created if we had used an external file for loading the database [the discussion of the In-line Resource (page 736 ) refactoring explains this approach]. To make the test clearer, we call intent-revealing methods that hide the details of how we use DbUnit to load the database and clean it out at the end of the test using Table Truncation Teardown . Here are the bodies of the Test Utility Methods used in this example:

private  void  insertRowsIntoDatabase(String  xmlString)
              throws  Exception  {
      IDataSet  dataSet  =  new  FlatXmlDataSet(new  StringReader(xmlString));
      DatabaseOperation.CLEAN_INSERT.
              execute(  getDbConnection(),  dataSet);
}

public  void  tearDown()  throws  Exception{
      emptyTable(TABLE_NAME);
}

public  void  emptyTable(String  tableName)  throws  Exception  {
      IDataSet  dataSet  =  new  DefaultDataSet(new  DefaultTable(tableName));
      DatabaseOperation.DELETE_ALL.
                  execute(getDbConnection(),  dataSet);
}

Of course, the implementations of these methods are specific to DbUnit; we must change them if we use some other member of the xUnit family.

Some other observations on these tests: To avoid an Eager Test (see Assertion Roulette on page 224 ), the assertion on each field appears in a separate test. This structure could result in Slow Tests (page 253 ) because these tests interact with a database. We could use Lazy Setup (page 435 ) or Suite Fixture Setup (page 441 ) to avoid setting up the fixture more than once as long as the resulting Shared Fixture (page 317 ) was not modified by any of the tests. (I chose not to further complicate this example by taking this tack.)

Further Reading

See the sidebar " Database as SUT API? " on page 336 for an example of when the back door is really a front door.


Database as SUT API?

A common technique for setting up test fixtures is Back Door Setup (see Back Door Manipulation on page 327 ); for verifying test outcomes, Back Door Verification (see Back Door Manipulation ) is a popular option. But when is a test that interacts directly with the database behind a SUT not considered to be going through the back door?

On a recent project, some friends were struggling with this very question, though at first they didn't realize it. One of their analysts (who was also a power user) seemed overly focused on the database schema. At first, they put this narrow focus down to the analyst's Powerbuilder background and tried to break him of the habit. That didn't work. The analyst just dug in his heels. The developers tried explaining that on agile projects it was important not to try to define the whole data schema at the beginning of the project; instead, the schema evolved as the requirements were implemented.

Of course, the analyst complained every time they modified the database schema because the changes broke all his queries. As the project unfolded, the other team members slowly started to understand that the analyst really did need a stable database against which to run queries. It was his way to verify the correctness of the data generated by the system.

Once they recognized this requirement, the developers were able to treat the query schema as a formal interface provided by the system. Customer tests were written against this interface and developers had to ensure that those tests still passed whenever they changed the database. To minimize the impact of database refactorings, they defined a set of query views that implemented this interface. This approach allowed them to refactor the database as needed.

When might you find yourself in this situation? Any time your customer applies reporting tools (such as Crystal Reports) to your database, an argument can be made as to whether part of the requirements is a stable reporting interface. Similarly, if the customer uses scripts (such as DTS or SQL) to load data into the database, there may be a requirement for a stable data loading interface.


Layer Test

Also known as

Single Layer Test, Testing by Layers, Layered Test

How can we verify logic independently when it is part of a layered architecture?

We write separate tests for each layer of the layered architecture.

image

It is difficult to obtain good test coverage when testing an entire application in a top-to-bottom fashion; we are bound to end up doing Indirect Testing (see Obscure Test on page 186 ) on some parts of the application. Many applications use a Layered Architecture [DDD, PEAA, WWW] to separate the major technical concerns. Most applications have some kind of presentation (user interface) layer, a business logic layer or domain layer, and a persistence layer. Some layered architectures have even more layers.

An application with a layered architecture can be tested more effectively by testing each layer in isolation.

How It Works

We design the SUT using a layered architecture that separates the presentation logic from the business logic and from any persistence mechanism or interfaces to other systems. 11 We put all business logic into a Service Layer [PEAA] that exposes the application functionality to the presentation layer as an API . We treat each layer of the architecture as a separate SUT. We write component tests for each layer independent of the other layers of the architecture. That is, for layer n of the architecture, the tests will take the place of layer n+1 ; we may optionally replace layer n-1 with a Test Double (page 522 ).

When to Use It

We can use a Layer Test whenever we have a layered architecture and we want to provide good test coverage of the logic in each layer. It can be much simpler to test each layer independently than it is to test all the layers at once. This is especially true when we want to do defensive coding for return values of calls across the layer boundary. In software that is working correctly, these errors "should never happen"; in real life, they do. To make sure our code handles these errors, we can inject these "never happen" scenarios as indirect inputs to our layer.

Layer Tests are very useful when we want to divide up the project team into subteams based on the technology in which the team members specialize. Each layer of an architecture tends to require different knowledge and often uses different technologies; therefore, the layer boundaries serve as natural team boundaries. Layer Tests can be a good way to nail down and document the semantics of the layer interfaces.

Even when we choose to use a Layer Test strategy, it is a good idea to include a few "top-to-bottom" tests just to verify that the various layers are integrated correctly. These tests need to cover only one or two basic scenarios; we don't need to test every business test condition because all of them have already been tested in the Layer Tests for at least one of the layers.

Most of the variations on this pattern reflect which layer is being tested independently of the other layers.

Variation: Presentation Layer Test

One could write a whole book just on patterns of presentation layer testing. The specific patterns depend on the nature of the presentation layer technology (e.g., graphical user interface, traditional Web interface, "smart" Web interface, Web services). Regardless of the technology, the key is to test the presentation logic separately from the business logic so that we don't have to worry about changes in the underlying logic affecting our presentation layer tests. (They are hard enough to automate well as it is!)

Another consideration is to design the presentation layer so that its logic can be tested independently of the presentation framework. Humble Dialog (see Humble Object on page 695 ) is the key design-for-testability pattern to apply here. In effect, we are defining sublayers within the presentation layer; the layer containing the Humble Dialogs is the "presentation graphic layer" and the layer we have made testable is the "presentation behavior layer." This separation of layers allows us to verify that buttons are activated, menu items are grayed out, and so on, without instantiating any of the real graphical objects.

Variation: Service Layer Test

The Service Layer is where most of our unit tests and component tests are traditionally concentrated. Testing the business logic using customer tests is a bit more challenging because testing the Service Layer via the presentation layer often involves Indirect Testing and Sensitive Equality (see Fragile Test on page 239 ) , either of which can lead to Fragile Tests and High Test Maintenance Cost (page 265 ). Testing the Service Layer directly helps avoid these problems.

To avoid Slow Tests (page 253 ), we usually replace the persistence layer with a Fake Database (see Fake Object on page 551 ) and then run the tests. In fact, most of the impetus behind a layered architecture is to isolate this code from the other, harder-to-test layers. Alistair Cockburn puts an interesting spin on this idea in his description of a Hexagonal Architecture at http://alistair.cockburn.us [WWW] .

The Service Layer may come in handy for other uses. It can be used to run the application in "headless" mode (without a presentation layer attached), such as when using macros to automate frequently done tasks in Microsoft Excel.

Variation: Persistence Layer Test

The persistence layer also needs to be tested. Round-trip tests will often suffice if the application is the only one that uses the data store. But these tests won't catch one kind of programming error: when we accidentally put information into the wrong columns. As long as the data type of the interchanged columns is compatible and we make the same error when reading the data, our round-trip tests will pass! This kind of bug won't affect the operation of our application but it might make support more difficult and it will cause problems in interactions with other applications.

When other applications also use the data store, it is highly advisable to implement at least a few layer-crossing tests that verify information is put into the correct columns of tables. We can use Back Door Manipulation (page 327 ) to either set up the database contents or to verify the post-test database contents.

Variation: Subcutaneous Test

A Subcutaneous Test is a degenerate form of Layer Test that bypasses the presentation layer of the system to interact directly with the Service Layer. In most cases, the Service Layer is not isolated from the layer(s) below; therefore, we test everything except the presentation. Use of a Subcutaneous Test does not require as strict a separation of concerns as does a Service Layer Test, which makes Subcutaneous Test easier to use when we are retrofitting tests onto an application that wasn't designed for testability. We should use a Subcutaneous Test whenever we are writing customer tests for an application and we want to ensure our tests are robust. A Subcutaneous Test is much less likely to be broken by changes to the application 12 because it does not interact with the application via the presentation layer; as a consequence, a whole category of changes won't affect it.

Variation: Component Test

A Component Test is the most general form of Layer Test, in that we can think of the layers being made up of individual components that act as "micro-layers." Component Tests are a good way to specify or document the behavior of individual components when we are doing component-based development and some of the components must be modified or built from scratch.

Implementation Notes

We can write our Layer Tests as either round-trip tests or layer-crossing tests. Each has advantages. In practice, we typically mix both styles of tests. The round-trip tests are easier to write (assuming we already have a suitable Fake Object available to use for layer n-1 ). We need to use layer-crossing tests, however, when we are verifying the error-handling logic in layer n .

Round-Trip Tests

A good starting point for Layer Tests is the round-trip test, as it should be sufficient for most Simple Success Tests (see Test Method on page 348 ). These tests can be written such that they do not care whether we have fully isolated the layer of interest from the layers below. We can either leave the real components in place so that they are exercised indirectly, or we can replace them with Fake Objects . The latter option is particularly useful when by a database or asynchronous mechanisms in the layer below lead to Slow Tests .

Controlling Indirect Inputs

We can replace a lower layer of the system with a Test Stub (page 529 ) that returns "canned" results based on what the client layer passes in a request (e.g., Customer 0001 is a valid customer, 0002 is a dormant customer, 0003 has three accounts). This technique allows us to test the client logic with well-understood indirect inputs from the layer below. It is particularly useful when we are automating Expected Exception Tests (see Test Method ) or when we are exercising behavior that depends on data that arrives from an upstream system. 13 The alternative is to use Back Door Manipulation to set up the indirect inputs.

Verifying Indirect Outputs

When we want to verify the indirect outputs of the layer of interest, we can use a Mock Object (page 544 ) or Test Spy (page 538 ) to replace the components in the layer below the SUT. We can then compare the actual calls made to the DOC with the expected calls. The alternative is to use Back Door Manipulation to verify the indirect outputs of the SUT after they have occurred.

Motivating Example

When trying to test all layers of the application at the same time, we must verify the correctness of the business logic through the presentation layer. The following test is a very simple example of testing some trivial business logic through a trivial user interface:

private  final  int  LEGAL_CONN_MINS_SAME  =  30;
public  void  testAnalyze_sameAirline_LessThanConnectionLimit()
throws  Exception  {
    //  setup
    FlightConnection  illegalConn  =
            createSameAirlineConn(  LEGAL_CONN_MINS_SAME  -  1);
    //  exercise
    FlightConnectionAnalyzerImpl  sut  =
             new  FlightConnectionAnalyzerImpl();
    String  actualHtml  =
             sut.getFlightConnectionAsHtmlFragment(
                           illegalConn.getInboundFlightNumber(),
                           illegalConn.getOutboundFlightNumber());
    //  verification
    StringBuffer  expected  =  new  StringBuffer();
    expected.append("<span  class="boldRedText">");
    expected.append("Connection  time  between  flight  ");
    expected.append(illegalConn.getInboundFlightNumber());
    expected.append("  and  flight  ");
    expected.append(illegalConn.getOutboundFlightNumber());
    expected.append("  is  ");
    expected.append(illegalConn.getActualConnectionTime());
    expected.append("  minutes.</span>");
    assertEquals("html",  expected.toString(),  actualHtml);
}

This test contains knowledge about the business layer functionality (what makes a connection illegal) and presentation layer functionality (how an illegal connection is presented). It also depends on the database because the FlightConnection s are retrieved from another component. If any of these areas change, this test must be revisited as well.

Refactoring Notes

We can split this test into two separate tests: one to test the business logic (What constitutes an illegal connection?) and one to test the presentation layer (Given an illegal connection, how should it be displayed to the user?). We would typically do so by duplicating the entire Testcase Class (page 373 ), stripping out the presentation layer logic verification from the business layer Test Methods, and stubbing out the business layer object(s) in the presentation layer Test Methods .

Along the way, we will probably find that we can reduce the number of tests in at least one of the Testcase Classes because few test conditions exist for that layer. In this example, we started out with four tests (the combinations of same/different airlines and time periods), each of which tested both the business and presentation layers; we ended up with four tests in the business layer (the original combinations but tested directly) and two tests in the presentation layer (formatting of legal and illegal connections). 14 Therefore, only the latter two tests need to be concerned with the details of the string formatting and, when a test fails, we know which layer holds the bug.

We can take our refactoring even further by using a Replace Dependency with Test Double (page 739 ) refactoring to turn this Subcutaneous Test into a true Service Layer Test .

Example: Presentation Layer Test

The following example shows the earlier test refactored to verify the behavior of the presentation layer when an illegal connection is requested. It stubs out the FlightConnAnalyzer and configures it with the illegal connection to return to the HtmlFacade when it is called. This technique gives us complete control over the indirect input of the SUT.

public  void  testGetFlightConnAsHtml_illegalConnection()
throws  Exception  {
    //  setup
    FlightConnection  illegalConn  =  createIllegalConnection();
    Mock  analyzerStub  =  mock(IFlightConnAnalyzer.class);
    analyzerStub.expects(once()).method("analyze")
            .will(returnValue(illegalConn));
    HTMLFacade  htmlFacade  =
            new  HTMLFacade((IFlightConnAnalyzer)analyzerStub.proxy());
    //  exercise
    String  actualHtmlString  =
            htmlFacade.getFlightConnectionAsHtmlFragment(
                                illegalConn.getInboundFlightNumber(),
                                illegalConn.getOutboundFlightNumber());
    //  verify
    StringBuffer  expected  =  new  StringBuffer();
    expected.append("<span  class="boldRedText">");
    expected.append("Connection  time  between  flight  ");
    expected.append(illegalConn.getInboundFlightNumber());
    expected.append("  and  flight  ");
    expected.append(illegalConn.getOutboundFlightNumber());
    expected.append("  is  ");
    expected.append(illegalConn.getActualConnectionTime());
    expected.append("  minutes.</span>");
    assertEquals("returned  HTML",
                       expected.toString(),
                       actualHtmlString);
}

We must compare the string representations of the HTML to determine whether the code has generated the correct response. Fortunately, we need only two such tests to verify the basic behavior of this component.

Example: Subcutaneous Test

Here's the original test converted into a Subcutaneous Test that bypasses the presentation layer to verify that the connection information is calculated correctly. Note the lack of any string manipulation in this test.

private  final  int  LEGAL_CONN_MINS_SAME  =  30;
public  void  testAnalyze_sameAirline_LessThanConnectionLimit()
throws  Exception  {
    //  setup
    FlightConnection  expectedConnection  =
           createSameAirlineConn(  LEGAL_CONN_MINS_SAME  -1);
    //  exercise
    IFlightConnAnalyzer  theConnectionAnalyzer  =
           new  FlightConnAnalyzer();
    FlightConnection  actualConnection  =
            theConnectionAnalyzer.getConn(
                      expectedConnection.getInboundFlightNumber(),
                      expectedConnection.getOutboundFlightNumber());
    //  verification
    assertNotNull("actual  connection",  actualConnection);
    assertFalse("IsLegal",  actualConnection.isLegal());
}

While we have bypassed the presentation layer, we have not attempted to isolate the Service Layer from the layers below. This omission could result in Slow Tests or Erratic Tests (page 228 ).

Example: Business Layer Test

The next example shows the same test converted into a Service Layer Test that is fully isolated from the layers below it. We have used JMock to replace these components with Mock Objects that verify the correct flights are being looked up and that inject the corresponding flight constructed into the SUT.

public  void  testAnalyze_sameAirline_EqualsConnectionLimit()
throws  Exception  {
    //  setup
    Mock  flightMgntStub  =  mock(FlightManagementFacade.class);
    Flight  firstFlight  =  createFlight();
    Flight  secondFlight  =  createConnectingFlight(
                                      firstFlight,  LEGAL_CONN_MINS_SAME);
    flightMgntStub.expects(once()).method("getFlight")
                           .with(eq(firstFlight.getFlightNumber()))
                           .will(returnValue(firstFlight));
    flightMgntStub.expects(once()).method("getFlight")
                           .with(eq(secondFlight.getFlightNumber()))
                           .will(returnValue(secondFlight));
    //  exercise
    FlightConnAnalyzer  theConnectionAnalyzer  =  new  FlightConnAnalyzer();
    theConnectionAnalyzer.facade  =
            (FlightManagementFacade)flightMgntStub.proxy();
    FlightConnection  actualConnection  =
           theConnectionAnalyzer.getConn(
                                         firstFlight.getFlightNumber(),
                                         secondFlight.getFlightNumber());
    //  verification
    assertNotNull("actual  connection",  actualConnection);
    assertTrue("IsLegal",  actualConnection.isLegal());
}

This test runs very quickly because the Service Layer is fully isolated from any underlying layers. It is also likely to be much more robust because it tests much less code.