Code Smells

Smells in This Chapter

       Obscure Test 186

       Conditional Test Logic 200

       Hard-to-Test Code 209

       Test Code Duplication 213

       Test Logic in Production 217

Obscure Test

Also known as

Long Test, Complex Test, Verbose Test

It is difficult to understand the test at a glance.

Automated tests should serve at least two purposes. First, they should act as documentation of how the system under test (SUT) should behave; we call this Tests as Documentation (see page 23 ). Second, they should be a self-verifying executable specification. These two goals are often contradictory because the level of detail needed for tests to be executable may make the test so verbose as to be difficult to understand.

Symptoms

We are having trouble understanding what behavior a test is verifying.

Impact

The first issue with an Obscure Test is that it makes the test harder to understand and therefore maintain. It will almost certainly preclude achieving Tests as Documentation, which in turn can lead to High Test Maintenance Cost (page 265 ).

The second issue with an Obscure Test is that it may allow bugs to slip through because of test coding errors hidden in the Obscure Test . This can result in Buggy Tests (page 260 ). Furthermore, a failure of one assertion in an Eager Test may hide many more errors that simply aren't run, leading to a loss of test debugging data.

Causes

Paradoxically, an Obscure Test can be caused by either too much information in the Test Method (page 348 ) or too little information. Mystery Guest is an example of too little information; Eager Test and Irrelevant Information are examples of too much information.

The root cause of an Obscure Test is typically a lack of attention to keeping the test code clean and simple. Test code is just as important as the production code, and it needs to be refactored just as often. A major contributor to an Obscure Test is a "just do it in-line" mentality when writing tests. Putting code in-line results in large, complex Test Methods because some things just take a lot of code to do.

The first few causes of Obscure Test discussed here relate to having the wrong information in the test:

  • Eager Test: The test verifies too much functionality in a single Test Method .
  • Mystery Guest: The test reader is not able to see the cause and effect between fixture and verification logic because part of it is done outside the Test Method .

The general problem of Verbose Tests —tests that use too much code to say what they need to say—can be further broken down into a number of root causes:

  • General Fixture: The test builds or references a larger fixture than is needed to verify the functionality in question.
  • Irrelevant Information: The test exposes a lot of irrelevant details about the fixture that distract the test reader from what really affects the behavior of the SUT.
  • Hard-Coded Test Data: Data values in the fixture, assertions, or arguments of the SUT are hard-coded in the Test Method, obscuring cause–effect relationships between inputs and expected outputs.
  • Indirect Testing: The Test Method interacts with the SUT indirectly via another object, thereby making the interactions more complex.
Cause: Eager Test

The test verifies too much functionality in a single Test Method .

Symptoms

The test goes on and on verifying this, that, and "everything but the kitchen sink." It is hard to tell which part is fixture setup and which part is exercising the SUT.

public  void  testFlightMileage_asKm2()  throws  Exception  {
      //  set  up  fixture
      //  exercise  constructor
      Flight  newFlight  =  new  Flight(validFlightNumber);
      //  verify  constructed  object
      assertEquals(validFlightNumber,  newFlight.number);
      assertEquals("",  newFlight.airlineCode);
      assertNull(newFlight.airline);
      //  set  up  mileage
      newFlight.setMileage(1122);
      //  exercise  mileage  translator
      int  actualKilometres  =  newFlight.getMileageAsKm();
      //  verify  results
      int  expectedKilometres  =  1810;
      assertEquals(  expectedKilometres,  actualKilometres);
      //  now  try  it  with  a  canceled  flight
      newFlight.cancel();
      try  {
          newFlight.getMileageAsKm();
          fail("Expected  exception");
      }  catch  (InvalidRequestException  e)  {
          assertEquals(  "Cannot  get  cancelled  flight  mileage",
                              e.getMessage());
      }
}

Root Cause

When executing tests manually, it makes sense to chain a number of logically distinct test conditions into a single test case to reduce the setup overhead of each test. This works because we have liveware (an intelligent human being) executing the tests, and this person can decide at any point whether it makes sense to keep going or whether the failure of a step is severe enough to abandon the execution of the test.

Possible Solution

When the tests are automated, it is better to have a suite of independent Single-Condition Tests (see page 45 ) as these provide much better Defect Localization (see page 22 ).

Cause: Mystery Guest

The test reader is not able to see the cause and effect between fixture and verification logic because part of it is done outside the Test Method .

Symptoms

Tests invariably require passing data to the SUT. The data used in the fixture setup and exercise SUT phases of the Four-Phase Test (page 358 ) define the pre-conditions of the SUT and influence how it should behave. The post-conditions (the expected outcomes) are reflected in the data passed as arguments to the Assertion Methods (page 362 ) in the verify outcome phase of the test.

When either the fixture setup or the result verification part of a test depends on information that is not visible within the test and the test reader finds it difficult to understand the behavior that is being verified without first finding and inspecting the external information, we have a Mystery Guest on our hands. Here's an example where we cannot tell what the fixture looks like, making it difficult to relate the expected outcome to the pre-conditions of the test:

public  void  testGetFlightsByFromAirport_OneOutboundFlight_mg()
                      throws  Exception  {
      loadAirportsAndFlightsFromFile("test-flights.csv");
      //  Exercise  System
      List  flightsAtOrigin  =  facade.getFlightsByOriginAirportCode(  "YYC");
      //  Verify  Outcome
      assertEquals(  1,  flightsAtOrigin.size());
      FlightDto  firstFlight  =  (FlightDto)  flightsAtOrigin.get(0);
      assertEquals(  "Calgary",  firstFlight.getOriginCity());
}

Impact

The Mystery Guest makes it hard to see the cause–effect relationship between the test fixture (the pre-conditions of the test) and the expected outcome of the test. As a consequence, the tests don't fulfill the role of Tests as Documentation . Even worse, someone may modify or delete the external resource without realizing the impact this action will have when the tests are run. This behavior smell has its own name: Resource Optimism (see Erratic Test on page 228 )!

If the Mystery Guest is a Shared Fixture (page 317 ), it may also lead to Erratic Tests if other tests modify it.

Root Cause

A test depends on mysterious external resources, making it difficult to understand the behavior that it is verifying. Mystery Guests may take many forms:

  • A filename of an existing external file is passed to a method of the SUT; the contents of the file should determine the behavior of the SUT.
  • The contents of a database record identified by a literal key are read into an object that is then used by the test or passed to the SUT.
  • The contents of a file are read and used in calls to Assertion Methods to verify the expected outcome.
  • A Setup Decorator (page 447 ) is used to create a Shared Fixture, and objects in this fixture are then referenced via variables within the result verification logic.
  • A General Fixture is set up using Implicit Setup (page 424 ), and the Test Methods then access them via instance variables or class variables.

All of these scenarios share a common outcome: It is hard to see the cause–effect relationship between the test fixture and the expected outcome of the test because the relevant data are not visible in the tests. If the contents of the data are not clearly described by the names we give to the variables and files that contain them, we have a Mystery Guest .

Possible Solution

Using a Fresh Fixture (page 311 ) built using In-line Setup (page 408 ) is the obvious solution for a Mystery Guest . When applied to the file example, this would involve creating the contents of the file as a string within our test so that the contents are visible and then writing them out to the file system [Setup External Resource (page 772 ) refactoring] or putting it into a file system Test Stub (page 529 ) as part of the fixture setup. 1 To avoid Irrelevant Information , we may want to hide the details of the construction behind one or more evocatively named Creation Methods (page 415 ) that append to the file's contents.

If we must use a Shared Fixture or Implicit Setup, we should consider using evocatively named Finder Methods (see Test Utility Method on page 599 ) to access the objects in the fixture. If we must use external resources such as files, we should put them into a special folder or directory and give them names that make it obvious what kind of data they hold.

Cause: General Fixture

The test builds or references a larger fixture than is needed to verify the functionality in question.

Symptoms

There seems to be a lot of test fixture being built—much more than would appear to be necessary for any particular test. It is hard to understand the cause–effect relationship between the fixture, the part of the SUT being exercised, and the expected outcome of a test.

Consider the following set of tests:

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);
}

From reading the exercise SUT and verifing outcome parts of the tests, it would appear that they need very different fixtures. Even though these tests are using a Fresh Fixture setup strategy, they are using the same fixture setup logic by calling the setupStandardAirportsAndFlights method. The name of the method is a clue to this classic but easily recognized example of a General Fixture . A more difficult case to diagnose would be if each test created the Standard Fixture (page 305 ) in-line or if each test created a somewhat different fixture but each fixture contained much more than was needed by each individual test.

We may also be experiencing Slow Tests (page 253 ) or a Fragile Fixture (see Fragile Test on page 239 ).

Root Cause

The most common cause of this problem is a test that uses a fixture that is designed to support many tests. Examples include the use of Implicit Setup or a Shared Fixture across many tests with different fixture requirements. This problem results in the fixture becoming large and difficult to understand. The fixture may also grow larger over time. The root cause is that both approaches rely on a Standard Fixture that must meet the requirements of all tests that use it. The more diverse the needs of those tests, the more likely we are to create a General Fixture .

Impact

When the test fixture is designed to support many different tests, it can be very difficult to understand how each test uses the fixture. This complexity reduces the likelihood of using Tests as Documentation and can result in a Fragile Fixture as people alter the fixture so that it can handle new tests. It can also result in Slow Tests because a larger fixture takes more time to build, especially if a file system or database is involved.

Possible Solution

We need to move to a Minimal Fixture (page 302 ) to address this problem. To do so, we can use a Fresh Fixture for each test. If we must use a Shared Fixture, we should consider applying the Make Resource Unique (page 737 ) refactoring to create a virtual Database Sandbox (page 650 ) for each test. 2

Cause: Irrelevant Information

The test exposes a lot of irrelevant details about the fixture that distract the test reader from what really affects the behavior of the SUT.

Symptoms

As test readers, we find it hard to determine which of the values passed to objects actually affect the expected outcome:

public  void  testAddItemQuantity_severalQuantity_v10(){
      //    Set  Up  Fixture
      Address  billingAddress  =
           createAddress(  "1222  1st  St  SW",  "Calgary",  "Alberta",
                                  "T2N  2V2",  "Canada");
      Address  shippingAddress  =
           createAddress(  "1333  1st  St  SW",  "Calgary",  "Alberta",
                                  "T2N  2V2",  "Canada");
      Customer  customer  =
           createCustomer(  99,  "John",  "Doe",  new  BigDecimal("30"),
                                       billingAddress,  shippingAddress);
      Product  product  =
           createProduct(  88,"SomeWidget",new  BigDecimal("19.99"));
      Invoice  invoice  =  createInvoice(customer);
      //  Exercise  SUT
      invoice.addItemQuantity(product,  5);
      //  Verify  Outcome
      LineItem  expected  =
            new  LineItem(invoice,  product,5,  new  BigDecimal("30"),
                               new  BigDecimal("69.96"));
      assertContainsExactlyOneLineItem(invoice,  expected);
}

Fixture setup logic may seem very long and complicated as it weaves together many interrelated objects. This makes it hard to determine what the test is verifying because the reader doesn't understand the pre-conditions of the test:

public  void  testGetFlightsByOriginAirport_TwoOutboundFlights()
         throws  Exception  {
     FlightDto  expectedCalgaryToSanFran  =  new  FlightDto();
     expectedCalgaryToSanFran.setOriginAirportId(calgaryAirportId);
     expectedCalgaryToSanFran.setOriginCity(CALGARY_CITY);
     expectedCalgaryToSanFran.setDestinationAirportId(sanFranAirportId);
     expectedCalgaryToSanFran.setDestinationCity(SAN_FRAN_CITY);
     expectedCalgaryToSanFran.setFlightNumber(
          facade.createFlight(calgaryAirportId,sanFranAirportId));
      FlightDto  expectedCalgaryToVan  =  new  FlightDto();
      expectedCalgaryToVan.setOriginAirportId(calgaryAirportId);
      expectedCalgaryToVan.setOriginCity(CALGARY_CITY);
      expectedCalgaryToVan.
                setDestinationAirportId(vancouverAirportId);
      expectedCalgaryToVan.setDestinationCity(VANCOUVER_CITY);
      expectedCalgaryToVan.setFlightNumber(facade.createFlight(
                calgaryAirportId,  vancouverAirportId));

The code that verifies the expected outcome of a test can also be too complicated to understand:

      List  lineItems  =  inv.getLineItems();
      assertEquals("number  of  items",  lineItems.size(),  2);
      //    verify  first  item
      LineItem  actual  =  (LineItem)lineItems.get(0);
      assertEquals(expItem1.getInv(),  actual.getInv());
      assertEquals(expItem1.getProd(),  actual.getProd());
      assertEquals(expItem1.getQuantity(),  actual.getQuantity());
      //    verify  second  item
      actual  =  (LineItem)lineItems.get(1);
      assertEquals(expItem2.getInv(),  actual.getInv());
      assertEquals(expItem2.getProd(),  actual.getProd());
      assertEquals(expItem2.getQuantity(),  actual.getQuantity());
}

Root Cause

A test contains a lot of data, either as Literal Values (page 714 ) or as variables. Irrelevant Information often occurs in conjunction with Hard-Coded Test Data or a General Fixture but can also arise because we make visible all data the test needs to execute rather than focusing on the data the test needs to be understood . When writing tests, the path of least resistance is to use whatever methods are available (on the SUT and other objects) and to fill in all parameters with values, whether or not they are relevant to the test.

Another possible cause is when we include all the code needed to verify the outcome using Procedural State Verification (see State Verification on page 462 ) rather than using a much more compact "declarative" style to specify the expected outcome.

Impact

It is hard to achieve Tests as Documentation if the tests contain many seemingly random bits of Obscure Test that don't clearly link the pre-conditions with the post-conditions. Likewise, wading through many steps of fixture setup or result verification logic can result in High Test Maintenance Cost and can increase the likelihood of Production Bugs (page 268 ) or Buggy Tests .

Possible Solution

The best way to get rid of Irrelevant Information in fixture setup logic is to replace direct calls to the constructor or Factory Methods [GOF] with calls to Parameterized Creation Methods (see Creation Method ) that take only the relevant information as parameters. Fixture values that do not matter to the test (i.e., those that do not affect the expected outcome) should be defaulted within Creation Methods or replaced by Dummy Objects (page 728 ). In this way we say to the test reader, "The values you don't see don't affect the expected outcome." We can replace fixture values that appear in both the fixture setup and outcome verification parts of the test with suitably initialized named constants as long as we are using a Fresh Fixture approach to fixture setup.

To hide Irrelevant Information in result verification logic, we can use assertions on entire Expected Objects (see State Verification ), rather than asserting on individual fields, and we can create Custom Assertions (page 474 ) that hide complex procedural verification logic.

Cause: Hard-Coded Test Data

Data values in the fixture, assertions, or arguments of the SUT are hard-coded in the Test Method, obscuring cause–effect relationships between inputs and expected outputs.

Symptoms

As test readers, we find it difficult to determine how various hard-coded (i.e., literal) values in the test are related to one another and which values should affect the behavior of the SUT. We may also encounter behavior smells such as Erratic Tests .

public  void  testAddItemQuantity_severalQuantity_v12(){
    //    Set  Up  Fixture
    Customer  cust  =  createACustomer(new  BigDecimal("30"));
    Product  prod  =  createAProduct(new  BigDecimal("19.99"));
    Invoice  invoice  =  createInvoice(cust);
    //  Exercise  SUT
    invoice.addItemQuantity(prod,  5);
    //  Verify  Outcome
    LineItem  expected  =  new  LineItem(invoice,  prod,  5,
            new  BigDecimal("30"),  new  BigDecimal("69.96"));
    assertContainsExactlyOneLineItem(invoice,  expected);
}

This specific example isn't so bad because there aren't very many literal values. If we aren't good at doing math in our heads, however, we might miss the relationship between the unit price ($19.99), the item quantity (5), the discount (30%), and the total price ($69.96).

Root Cause

Hard-Coded Test Data occurs when a test contains a lot of seemingly unrelated Literal Values . Tests invariably require passing data to the SUT. The data used in the fixture setup and exercise SUT phases of the Four-Phase Test define the preconditions of the SUT and influence how it should behave. The post-conditions (the expected outcomes) are reflected in the data passed as arguments to the Assertion Methods in the verify outcome phase of the test. When writing tests, the path of least resistance is to use whatever methods are available (on the SUT and other objects) and to fill in all parameters with values, whether or not they are relevant to the test.

When we use "cut-and-paste" reuse of test logic, we find ourselves replicating the literal values to the derivative tests.

Impact

It is hard to achieve Tests as Documentation if the tests contain many seemingly random bits of Obscure Test that don't clearly link the pre-conditions with the post-conditions. A few literal parameters might not seem like a bad thing—after all, they don't require us to make that much more effort to understand a test. As the number of literal values grows, however, it can become much more difficult to understand a test. This is especially true when the signal-to-noise ratio drops dramatically because the majority of the values are irrelevant to the test.

The second major impact occurs when collisions between tests occur because the tests are using the same values. This situation happens only when we use a Shared Fixture because a Fresh Fixture strategy shouldn't litter the scene with any objects with which a subsequent test can collide.

Possible Solution

The best way to get rid of the Obscure Test smell is to replace the literal constants with something else. Fixture values that determine which scenario is being executed (e.g., type codes) are probably the only ones that are reasonable to leave as literals—but even these values can be converted to named constants.

Fixture values that do not matter to the test (i.e., those that do not affect the expected outcome) should be defaulted within Creation Methods . In this way we say to the test reader, "The values you don't see don't affect the expected outcome." We can replace fixture values that appear in both the fixture setup and outcome verification parts of the test with suitably initialized named constants as long as we are using a Fresh Fixture approach to fixture setup.

Values in the result verification logic that are based on values used in the fixture or that are used as arguments of the SUT should be replaced with Derived Values (page 718 ) to make those calculations obvious to the test reader.

If we are using any variant of Shared Fixture , we should try to use Distinct Generated Values (see Generated Value on page 723 ) to ensure that each time a test is run, it uses a different value. This consideration is especially important for fields that serve as unique keys in databases. A common way of encapsulating this logic is to use Anonymous Creation Methods (see Creation Method ).

Cause: Indirect Testing

The Test Method interacts with the SUT indirectly via another object, thereby making the interactions more complex.

Symptoms

A test interacts primarily with objects other than the one whose behavior it purports to verify. The test must construct and interact with objects that contain references to the SUT rather than with the SUT itself. Testing business logic through the presentation layer is a common example of Indirect Testing .

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);
}

Impact

It may not be possible to test "anything that could possibly break" in the SUT via the intermediate object. Indeed, such tests are unlikely to be very clear or understandable. They certainly will not result in Tests as Documentation .

Indirect Testing may result in Fragile Tests because changes in the intermediate objects may require modification of the tests even when the SUT is not modified.

Root Cause

The SUT may be "private" to the class being used to access it from the test. It may not be possible to create the SUT directly because the constructors themselves are private. This problem is just one sign that the software is not designed for testability.

It may be that the actual outcome of exercising the SUT cannot be observed directly. In such a case, the expected outcome of the test must be verified through an intermediate object.

Possible Solution

It may be necessary to improve the design-for-testability of the SUT to remove this smell. We might be able to expose the SUT directly to the test by using an Extract Testable Component refactoring (a variant of the Sprout Class [WEwLC] refactoring). This approach may result in an untestable Humble Object (page 695 ) and an easily tested object that contains most or all of the actual logic.

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());
}

Sometimes we may be forced to interact with the SUT indirectly because we cannot refactor the code to expose the logic we are trying to test. In these cases, we should encapsulate the complex logic forced by Indirect Testing behind suitably named Test Utility Methods . Similarly, fixture setup can be hidden behind Creation Methods and result verification can be hidden by Verification Methods (see Custom Assertion ). Both are examples of SUT API Encapsulation (see Test Utility Method ).

public  void  testAnalyze_sameAirline_LessThanConnLimit()
throws  Exception  {
    //  setup
    FlightConnection  illegalConn  =
            createSameAirlineConn(  LEGAL_CONN_MINS_SAME  -  1);
    FlightConnectionAnalyzerImpl  sut  =
            new  FlightConnectionAnalyzerImpl();
    //  exercise  SUT
    String  actualHtml  =
            sut.getFlightConnectionAsHtmlFragment(
                           illegalConn.getInboundFlightNumber(),
                           illegalConn.getOutboundFlightNumber());
    //  verification
    assertConnectionIsIllegal(illegalConn,  actualHtml);
}

The following Custom Assertion hides the ugliness of extracting the business result from the presentation noise. It was created by doing a simple Extract Method [Fowler] refactoring on the test. Of course, this example would be more robust if it searched inside the HTML for key strings rather than building up the entire expected string and comparing it all at once. Other Presentation Layer Tests (see Layer Test on page 337 ) might then verify that the presentation logic is formatting the HTML string properly.

private  void  assertConnectionIsIllegal(  FlightConnection  conn,
                                                          String  actualHtml)  {
    //  set  up  expected  value
    StringBuffer  expected  =  new  StringBuffer();
    expected.append("<span  class="boldRedText">");
    expected.append("Connection  time  between  flight  ");
    expected.append(conn.getInboundFlightNumber());
    expected.append("  and  flight  ");
    expected.append(conn.getOutboundFlightNumber());
    expected.append("  is  ");
    expected.append(conn.getActualConnectionTime());
    expected.append("  minutes.</span>");
    //  verification
    assertEquals("html",  expected.toString(),  actualHtml);
}

Solution Patterns

A good test strategy helps keep the test code understandable. Nevertheless, just as "no battle plan survives the first contact with the enemy," no test infrastructure can anticipate all needs of all tests. We should expect the test infrastructure to evolve as the software matures and our test automation skills improve.

We can reuse test logic for several scenarios by having several tests call Test Utility Methods or by asking a common Parameterized Test (page 607 ) to pass in the already built test fixture or Expected Objects .

Writing tests in an "outside-in" way can minimize the likelihood of producing an Obscure Test that might then need to be refactored. This approach starts by outlining the Four-Phase Test using calls to nonexistent Test Utility Methods . Once we are satisfied with these tests, we can write the utility methods needed to run them. By writing the tests first, we gain a better understanding of what the utility methods need to do for us to make writing the tests as simple as possible. The "test-infected" will, of course, write Test Utility Tests (see Test Utility Method ) before writing the Test Utility Methods .

Conditional Test Logic

Also known as

Indented Test Code

A test contains code that may or may not be executed.

A Fully Automated Test (see page 26 ) is just code that verifies the behavior of other code. But if this code is complicated, how do we verify that it works properly? We could write tests for our tests—but when would this recursion stop? The simple answer is that Test Methods (page 348 ) must be simple enough to not need tests.

Conditional Test Logic is one factor that makes tests more complicated than they really should be.

Symptoms

As a code smell, Conditional Test Logic may not produce any behavioral symptoms but its presence should be reasonably obvious to the test reader. View any control structures within a Test Method with extreme suspicion! The test reader may also wonder which code path is the one that is being executed. The following is an example of Conditional Test Logic that involves both looping and if statements:

      //     verify  Vancouver  is  in  the  list
      actual  =  null;
      i  =  flightsFromCalgary.iterator();
      while  (i.hasNext())  {
          FlightDto  flightDto  =  (FlightDto)  i.next();
          if  (flightDto.getFlightNumber().equals(
                  expectedCalgaryToVan.getFlightNumber()))
          {
              actual  =  flightDto;
              assertEquals("Flight  from  Calgary  to  Vancouver",
                                expectedCalgaryToVan,
                                flightDto);
              break;
          }
      }
}

This code begs the question, "What is this test code doing and how do we know that it is doing it correctly?" One behavioral symptom may be the presence of the related project-level smell High Test Maintenance Cost (page 265 ), which may be caused by the complexity introduced by the Conditional Test Logic .

Impact

Conditional Test Logic makes it difficult to know exactly what a test is going to do when it really matters. Code that has only a single execution path always executes in exactly the same way. Code that has multiple execution paths presents much greater challenges and does not inspire as much confidence about its outcome.

To increase our confidence in production code, we can write Self-Checking Tests (see page 26 ) that exercise the code. How can we increase our confidence in the test code if it executes differently each time we run it? It is hard to know (or prove) that the test is verifying the behavior we want it to verify. A test that has branches or loops, or that uses different values each time it is run, can be very difficult to debug simply because it isn't completely deterministic.

A related issue is that Conditional Test Logic makes writing the test correctly a more difficult task. Because the test itself cannot be tested easily, how do we know that it will actually detect the bugs it is intended to catch? [This is a general problem with Obscure Tests (page 186 ); they are more likely to result in Buggy Tests (page 260 ) than simple code.]

Causes

Test automaters may introduce Conditional Test Logic for several reasons:

  • They may use if statements to steer execution to a fail statement or to avoid executing certain pieces of test code when the SUT fails to return valid data.
  • They may use loops to verify the contents of collections of objects ( Conditional Verification Logic ). This may also result in an Obscure Test .
  • They may use Conditional Test Logic to verify complex objects or polymorphic data structures (another form of Conditional Verification Logic ). This is just a Foreign Method [Fowler] implementation of the equals method.
  • They may use Conditional Test Logic to initialize the test fixture or Expected Object (see State Verification on page 462 ) so they can reuse a single test to verify several different cases ( Flexible Test ).
  • They may use if statements to avoid tearing down nonexistent fixture objects ( Complex Teardown ).

Some of these causes are worth examining in more detail.

Cause: Flexible Test

The test code verifies different functionality depending on when or where it is run.

Symptoms

The test contains conditional logic that does different things depending on the current environment. Most commonly this functionality takes the form of Conditional Test Logic to build different versions of the expected results based on some factor external to the test.

Consider the following test, which gets the current time so that it can determine what the output of the SUT should be:

public  void  testDisplayCurrentTime_whenever()  {
     //  fixture  setup
     TimeDisplay  sut  =  new  TimeDisplay();
     //  exercise  SUT
     String  result  =  sut.getCurrentTimeAsHtmlFragment();
     //  verify  outcome
     Calendar  time  =  new  DefaultTimeProvider().getTime();
     StringBuffer  expectedTime  =  new  StringBuffer();
     expectedTime.append("<span  class=\"tinyBoldText\">");
     if  ((time.get(Calendar.HOUR_OF_DAY)  ==  0)
         &&  (time.get(Calendar.MINUTE)  <=  1))  {
         expectedTime.append(  "Midnight");
     }  else  if  ((time.get(Calendar.HOUR_OF_DAY)  ==  12)
                     &&  (time.get(Calendar.MINUTE)  ==  0))  {  //  noon
         expectedTime.append("Noon");
     }  else    {
         SimpleDateFormat  fr  =  new  SimpleDateFormat("h:mm  a");
         expectedTime.append(fr.format(time.getTime()));
     }
     expectedTime.append("</span>");
     assertEquals(  expectedTime,  result);
}

Root Cause

A Flexible Test is caused by a lack of control of the environment. The test automater probably wasn't able to decouple the SUT from its dependencies and decided to adapt the test logic based on the state of the environment.

Impact

The first issue is that using a Flexible Test makes the test harder to understand and therefore to maintain. The second issue is that we don't know which test scenarios are actually being exercised and whether all scenarios are, in fact, exercised regularly. For example, in our sample test, is the midnight scenario ever exercised? How often? Probably rarely, if ever, because the test would have to be run at exactly midnight—an unlikely event, even if we timed the nightly build such that it ran over midnight.

Possible Solution

A Flexible Test is best addressed by decoupling the SUT from whatever dependencies prompted the test automater to make the test flexible. This involves refactoring the SUT to support substitutable dependency . We can then replace the dependency with a Test Double (page 522 ), such as a Test Stub (page 529 ) or Mock Object (page 544 ), and write separate tests for each circumstance previously covered by the Flexible Test .

Cause: Conditional Verification Logic

Conditional Test Logic (page 200 ) may also create problems when it is used to verify the expected outcome. This issue usually arises when the tester tries to prevent the execution of assertions if the SUT fails to return the right objects or uses loops to verify the contents of collections returned by the SUT.

      //     verify  Vancouver  is  in  the  list
      actual  =  null;
      i  =  flightsFromCalgary.iterator();
      while  (i.hasNext())  {
          FlightDto  flightDto  =  (FlightDto)  i.next();
          if  (flightDto.getFlightNumber().equals(
                  expectedCalgaryToVan.getFlightNumber()))
          {
              actual  =  flightDto;
              assertEquals("Flight  from  Calgary  to  Vancouver",
                                expectedCalgaryToVan,
                                flightDto);
              break;
          }
      }
}

Possible Solution

We can replace the if statements that steer execution to a call to fail with a Guard Assertion (page 490 ) that causes the test to fail before we reach the code we don't want to execute. This works well unless the test is an Expected Exception Test (see Test Method . ) In the latter case, we should use the standard Expected Exception Test coding idiom for the xUnit family member and language.

We can replace Conditional Test Logic for verification of complex objects with an Equality Assertion (see Assertion Method on page 362 ) on an Expected Object . If the production code's equals method is too strict, we can use a Custom Assertion (page 474 ) to define test-specific equality .

We should move any loops in the verification logic to a Custom Assertion. We can then verify this assertion's behavior by using Custom Assertion Tests (see Custom Assertion ).

We can reuse test logic in several tests by calling a Test Utility Method (page 599 ) or a common Parameterized Test (page 607 ) that passes in the already built test fixture and Expected Objects .

Cause: Production Logic in Test
Symptoms

Some forms of Conditional Test Logic are found in the result verification section of our tests. Let us look more closely inside the loops of this test:

public  void  testCombinationsOfInputValues()  {
    //  Set  up  fixture
    Calculator  sut  =  new  Calculator();
    int  expected;    //  TBD  inside  loops

    for  (int  i  =  0;  i  <  10;  i++)  {
        for  (int  j  =  0;  j  <  10;  j++)  {
            //  Exercise  SUT
            int  actual  =  sut.calculate(  i,  j  );

            //  Verify  result
            if  (i==3  &  j==4)    //  special  case
                expected  =  8;
            else
                expected  =  i+j;

            assertEquals(message(i,j),  expected,  actual);
        }
    }
}

private  String  message(int  i,  int  j)  {
    return  "Cell(  "  +  String.valueOf(i)+  ","
                            +  String.valueOf(j)  +  ")";
}

The nested loops in this Loop-Driven Test (see Parameterized Test ) exercise the SUT with various combinations of values of i and j as inputs. Here we will focus on the Conditional Test Logic inside the loop.

Root Cause

This Production Logic in Test is a direct result of wanting to verify multiple test conditions in a single Test Method . Given that multiple input values are passed to the SUT, we should also have multiple expected results. It is hard to enumerate the expected result for each set of inputs if we pass in many combinations of several input arguments to the SUT in nested loops. A common solution to this problem is to use a Calculated Value (see Derived Value on page 718 ) based on the inputs. The potential downfall (as we see here) is that we find ourselves replicating the expected SUT logic inside our test to calculate the expected values for assertions.

Possible Solution

If at all possible, it is better to enumerate the sets of precalculated values with which to test the SUT. The following example tests the same logic using a (smaller) set of enumerated values:

public  void  testMultipleValueSets()  {
    //  Set  Up  Fixture
    Calculator  sut  =  new  Calculator();
    TestValues[]  testValues  =  {
                          new  TestValues(1,2,3),
                          new  TestValues(2,3,5),
                          new  TestValues(3,4,8),  //  special  case!
                          new  TestValues(4,5,9)
                                              };

    for  (int  i  =  0;  i  <  testValues.length;  i++)  {
        TestValues  values  =  testValues[i];
        //  Exercise  SUT
        int  actual  =  sut.calculate(  values.a,  values.b);
        //  Verify  Result
        assertEquals(message(i),  values.expectedSum,  actual);
    }
}

private  String  message(int  i)  {
    return  "Row  "+  String.valueOf(i);
}

Cause: Complex Teardown
Symptoms

Complex fixture teardown code is more likely to leave the test environment corrupted if it does not clean up after itself correctly. It is hard to verify that teardown code has been written correctly, and such code can easily result in "data leaks" that may later cause this or other tests to fail for no apparent reason. Consider this example:

public  void  testGetFlightsByOrigin_NoInboundFlight_SMRTD()
              throws  Exception  {
      //  Set  Up  Fixture
      BigDecimal  outboundAirport  =  createTestAirport("1OF");
      BigDecimal  inboundAirport  =  null;
      FlightDto  expFlightDto  =  null;
      try  {
          inboundAirport  =  createTestAirport("1IF");
          expFlightDto  =
                  createTestFlight(outboundAirport,  inboundAirport);
            //  Exercise  System
            List  flightsAtDestination1  =
                    facade.getFlightsByOriginAirport(inboundAirport);
            //  Verify  Outcome
            assertEquals(0,flightsAtDestination1.size());
      }  finally  {
            try  {
                facade.removeFlight(expFlightDto.getFlightNumber());
            }  finally  {
                  try  {
                      facade.removeAirport(inboundAirport);
                  }  finally    {
                        facade.removeAirport(outboundAirport);
                  }
            }
      }
}

Root Cause

Teardown is typically required only when we use persistent resources that are beyond the reach of our garbage collection system. Complex Teardown occurs when many such resources are used in the same Test Method .

Possible Solution

To avoid complex teardown logic, we should use Implicit Teardown (page 516 ), which will make the code both reusable and testable, or Automated Teardown (page 503 ), which can be verified with automated unit tests. We can also eliminate the need to tear down any fixture objects by using a Fresh Fixture (page 311 ) strategy and by avoiding the use of any persistent objects in our tests by using some sort of Test Double .

Cause: Multiple Test Conditions
Symptoms

A test tries to apply the same test logic to many sets of input values, each with its own corresponding expected result. In the following example, the test iterates over a collection of test values and applies the test logic to each set:

public  void  testMultipleValueSets()  {
     //  Set  Up  Fixture
     Calculator  sut  =  new  Calculator();
     TestValues[]  testValues  =  {
                            new  TestValues(1,2,3),
                            new  TestValues(2,3,5),
                            new  TestValues(3,4,8),  //  special  case!
                            new  TestValues(4,5,9)
                                              };

    for   (int  i  =  0;  i  <  testValues.length;  i++)  {
        TestValues  values  =  testValues[i];
        //  Exercise  SUT
        int  actual  =  sut.calculate(  values.a,  values.b);
        //  Verify  Outcome
        assertEquals(message(i),  values.expectedSum,  actual);
    }
}

private  String  message(int  i)  {
    return  "Row  "+  String.valueOf(i);
}

Root Cause

The test automater is trying to test many test conditions using the same test logic in a single Test Method . In the preceding example, it is fairly simple Conditional Test Logic . Matters could be a lot worse if the code contained multiple nested loops and maybe even if statements to calculate different cases of the expected values.

Possible Solution

Of all sources of Conditional Test Logic, Multiple Test Conditions is probably the most innocuous. Other than scaring the test reader, the main impact of such a test is that it stops executing at the first failure and doesn't provide Defect Localization (see page 22 ) when a bug is introduced into the code. The readability issue can easily be addressed by using an Extract Method [Fowler] refactoring to create a Parameterized Test call from within the loop. The lack of Defect Localization can be addressed by calling the Parameterized Test from a separate Test Method for each test condition. For large sets of values, a Data-Driven Test (page 288 ) might be a better solution.

Hard-to-Test Code

Code is difficult to test.

Automated testing is a powerful tool that helps us develop software quickly even when we have a large code base to maintain. Of course, it provides these benefits only if most of our code is protected by Fully Automated Tests (see page 26 ). The effort of writing these tests must be added to the effort of writing the product code they verify. Not surprisingly, we would prefer to make it easy to write the automated tests. 3

Hard-to-Test Code is one factor that makes it difficult to write complete, correct automated tests in a cost-efficient manner.

Symptoms

Some kinds of code are inherently difficult to test—GUI components, multithreaded code, and test code, for example. It may be difficult to get at the code to be tested because it is not visible to a test. It may be problematic to compile a test because the code is too highly coupled to other classes. It may be hard to create an instance of the object because the constructors don't exist, are private, or take too many other objects as parameters.

Impact

Whenever we have Hard-to-Test Code , we cannot easily verify the quality of that code in an automated way. While manual quality assessment is often possible, it doesn't scale very well because the effort to perform this assessment after each code change usually means it doesn't get done. Nor is this strategy readily repeated without a large test documentation cost.

Solution Patterns

A better solution is to make the code more amenable to testing. This topic is big enough that it warrants a whole chapter of its own, but this section covers a few of the highlights.

Causes

Also known as

Hard-Coded Dependency

There are a number of reasons for Hard-to-Test Code ; the most common causes are discussed here.

Cause: Highly Coupled Code
Symptoms

A class cannot be tested without also testing several other classes.

Impact

Code that is highly coupled to other code is very difficult to unit test because it won't execute in isolation.

Root Cause

Highly Coupled Code can be caused by many factors, including poor design, lack of object-oriented design experience, and lack of a reward structure that encourages decoupling.

Possible Solution

The key to testing overly coupled code is to break the coupling. This happens naturally when we are doing test-driven development.

A technique that we often use to decouple code for the purpose of testing is a Test Double (page 522 ) or, more specifically, a Test Stub (page 529 ) or Mock Object (page 544 ). This topic is covered in much more detail in Chapter 11 , Using Test Doubles .

Retrofitting tests onto existing code is a more challenging task, especially when we are dealing with a legacy code base. This is a big enough topic that Michael Feathers wrote a whole book on techniques for doing this, titled Working Effectively with Legacy Code [WEwLC] .

Cause: Asynchronous Code
Symptoms

A class cannot be tested via direct method calls. The test must start an executable (such as a thread, process, or application) and wait until its start-up has finished before interacting with the executable.

Impact

Code that has an asynchronous interface is hard to test because the tests of these elements must coordinate their execution with that of the SUT. This requirement can add a lot of complexity to the tests and causes them to take much, much longer to run. The latter issue is a major concern with unit tests, which must run very quickly to ensure that developers will run them frequently.

Root Cause

The code that implements the algorithm we wish to test is highly coupled to the active object in which it normally executes.

Possible Solution

The key to testing asynchronous code is to separate the logic from the asynchronous access mechanism. The design-for-testability pattern Humble Object (page 695 ; including Humble Dialog and Humble Executable ) is a good example of a way to restructure otherwise asynchronous code so it can be tested in a synchronous manner.

Cause: Untestable Test Code
Symptoms

The body of a Test Method (page 348 ) is obscure enough ( Obscure Test; see page 186 ) or contains enough Conditional Test Logic (page 200 ) that we wonder whether the test is correct.

Impact

Any Conditional Test Logic within a Test Method has a higher probability of producing Buggy Tests (page 260 ) and will likely result in High Test Maintenance Cost (page 265 ). Too much code in the test method body can make the test hard to understand and hard to construct correctly.

Root Cause

The code within the body of the Test Method is inherently hard to test using a Self-Checking Test (see page 26 ). To do so, we would have to replace the SUT with a Test Double that injects the target error and then run the test method inside another Expected Exception Test (see Test Method ) method—much too much trouble to bother with in all but the most unusual circumstances.

Possible Solution

We can remove the need to test the body of a Test Method by making it extremely simple and relocating any Conditional Test Logic from it into Test Utility Methods (page 599 ), for which we can easily write Self-Checking Tests .

Test Code Duplication

The same test code is repeated many times.

Many of the tests in a suite need to do similar things. For example, tests often exercise scenarios that are variations on the same theme. Tests may require similar fixture setup or result verification logic. In some cases, even the exercise SUT phase of many tests involves repeating the same nontrivial logic.

The need for tests to do similar things often results in Test Code Duplication.

Symptoms

Several tests may contain a common subset of essentially the same statements, as in the following example:

public  void  testInvoice_addOneLineItem_quantity1_b()  {
        //  Exercise
        inv.addItemQuantity(product,  QUANTITY);
        //  Verify
        List  lineItems  =  inv.getLineItems();
        assertEquals("number  of  items",  lineItems.size(),  1);
        //  Verify  only  item
        LineItem  expItem  =  new  LineItem(inv,  product,  QUANTITY);
        LineItem  actual  =  (LineItem)lineItems.get(0);
        assertEquals(expItem.getInv(),  actual.getInv());
        assertEquals(expItem.getProd(),  actual.getProd());
        assertEquals(expItem.getQuantity(),  actual.getQuantity());
}

public  void  testRemoveLineItemsForProduct_oneOfTwo()  {
        //  Set  up
        Invoice  inv  =  createAnonInvoice();
        inv.addItemQuantity(product,  QUANTITY);
        inv.addItemQuantity(anotherProduct,  QUANTITY);
        LineItem  expItem  =  new  LineItem(inv,  product,  QUANTITY);
        //  Exercise
        inv.removeLineItemForProduct(anotherProduct);
        //  Verify
        List  lineItems  =  inv.getLineItems();
        assertEquals("number  of  items",  lineItems.size(),  1);
        LineItem  actual  =  (LineItem)lineItems.get(0);
        assertEquals(expItem.getInv(),  actual.getInv());
        assertEquals(expItem.getProd(),  actual.getProd());
        assertEquals(expItem.getQuantity(),  actual.getQuantity());
}

A single test may also contain repeated groups of similar statements:

public  void  testInvoice_addTwoLineItems_sameProduct()  {
      Invoice  inv  =  createAnonInvoice();
      LineItem  expItem1  =  new  LineItem(inv,  product,  QUANTITY1);
      LineItem  expItem2  =  new  LineItem(inv,  product,  QUANTITY2);
      //  Exercise
      inv.addItemQuantity(product,  QUANTITY1);
      inv.addItemQuantity(product,  QUANTITY2);
      //  Verify
      List  lineItems  =  inv.getLineItems();
      assertEquals("number  of  items",  lineItems.size(),  2);
      //      Verify  first  item
      LineItem  actual  =  (LineItem)lineItems.get(0);
      assertEquals(expItem1.getInv(),  actual.getInv());
      assertEquals(expItem1.getProd(),  actual.getProd());
      assertEquals(expItem1.getQuantity(),  actual.getQuantity());
      //      Verify  second  item
      actual  =  (LineItem)lineItems.get(1);
      assertEquals(expItem2.getInv(),  actual.getInv());
      assertEquals(expItem2.getProd(),  actual.getProd());
      assertEquals(expItem2.getQuantity(),  actual.getQuantity());
}

Both of the preceding examples exhibit Test Code Duplication that is easily noticed. By comparison, it is more challenging to identify duplication when it occurs across Test Methods (page 348 ) that reside in different Testcase Classes (page 373 ).

Impact

"Cut and paste" often results in many copies of the same code. This code must be maintained every time the SUT is modified in a way that affects the semantics (e.g., number of arguments, argument attributes, returned object attributes, calling sequences) of its methods. This necessity can greatly increase the cost to introduce new functionality ( High Test Maintenance Cost ; see page 265 ) because of the effort involved in updating all tests that contain copies of the affected code.

Causes

Cause: Cut-and-Paste Code Reuse

"Cut and paste" is a powerful tool for writing code fast but it results in many copies of the same code, each of which must be maintained in parallel.

Root Cause

Cut-and-Paste Code Reuse is often the default way to reuse logic. Developers who focus on details of "how" to do something will often repeat the same code many times because they cannot (or do not take the time to) focus on the big picture (the intent) of the test.

A contributing factor may be a lack of refactoring skills or refactoring experience that keeps developers from extracting the big picture from the detailed code they have written. Of course, time pressure may also be the culprit that keeps the refactoring from occurring. As a result, test code grows more complicated over time rather than becoming simpler.

Possible Solution

Once Test Code Duplication has occurred, the best solution is to use an Extract Method [Fowler] refactoring to create a Test Utility Method (page 599 ) from one of the examples and then to generalize that method to handle each of the copies. When the Test Code Duplication consists of fixture setup logic, we end up with Creation Methods (page 415 ) or Finder Methods (see Test Utility Method ). When the logic carries out result verification, we end up with Custom Assertions (page 474 ) or Verification Methods (see Custom Assertion ).

We can use an Introduce Parameter [JBrains] refactoring to convert any literal constants inside the extracted method into parameters that can be passed in to customize the method's behavior for each test that calls it.

More simply, we can avoid most Test Code Duplication by writing the Test Methods in an "outside-in" manner, focusing on their intent. Whenever we need to do something that involves several lines of code, we simply call a nonexistent Test Utility Method to do it. We write all our tests this way and then fill in implementations of the Test Utility Methods to get the tests to compile and run. (Modern IDEs facilitate this process by providing automatic method skeleton generation at a click of the mouse.)

Cause: Reinventing the Wheel

While Cut-and-Paste Code Reuse deliberately makes copies of existing code to reduce the effort of writing tests, it is also possible to accidentally write the same sequence of statements in different tests.

Root Cause

This problem is primarily caused by a lack of awareness of which Test Utility Methods are available. It can also be caused by a predisposition to write one's own code rather than reuse code written by others.

Possible Solution

The technical solution is largely the same as for Cut-and-Paste Code Reuse but the process solution is somewhat different. The test automater must look around more places to discover which Test Utility Methods are available before reinventing the wheel (i.e., writing new code).

Further Reading

Test Code Duplication was first described in a paper at XP2001 called "Refactoring Test Code" [RTC] .

Test Logic in Production

The code that is put into production contains logic that should be exercised only during tests.

The SUT may contain logic that cannot be run in a test environment. Tests may require the SUT to behave in specific ways to allow full test coverage.

Symptoms

The logic in the SUT is there solely to support testing. This logic may be "extra stuff" that the tests require to gain access to the SUT's internal state for fixture setup or result verification purposes. It may also consist of changes that the logic of the system undergoes when it detects that it is being tested.

Impact

We would prefer not to end up with Test Logic in Production , as it can make the SUT more complex and opens the door to additional kinds of bugs that we would like to avoid. A system that behaves one way in the test lab and an entirely different way in production is a recipe for disaster!

Causes

Cause: Test Hook

Conditional logic within the SUT determines whether the "real" code or test-specific logic is run.

Symptoms

With this code smell, either there may be no behavioral symptoms or something may go wrong in production. We may see snippets of code in the SUT that look something like this:

if  (testing)  {
    return  hardCodedCannedData;
}  else  {  //  the  real  logic  ...
    return  gatheredData;
}


Ariane

The maiden flight of the Ariane 5 rocket was a complete disaster: The rocket blew up only 37 seconds after takeoff. The culprit was a seemingly innocuous bit of code that was used only while the rocket was on the ground but unfortunately was left running for the first 40 seconds of flight. When it tried to assign a 64-bit number representing the sideways velocity of the rocket to a 16-bit field, the navigation computer decided that the rocket was going the wrong way! It tried to correct the course, but the sudden change in direction tore the booster rocket apart. While this is not quite an example of Test Logic in Production (page 217 ), it certainly does illustrate the risks associated with this type of error.

Could this disaster have been prevented by use of automated tests? While it is difficult to say with certainty, and one could certainly claim that any number of process changes could have detected this problem before it occurred, it is conceivable that automated tests could have averted this catastrophe.

In particular, a test should have addressed the boundary condition—namely, what happens when a number exceeds the maximum value storable. Such a test would have prevented an exception from occurring for the first time ever in production.

In addition, the presence of the tests from the Ariane 4 version of the rocket would have documented the maximum down-range velocity. It is quite possible that these tests would have been updated when the Ariane 5 software was being developed and that the new tests would have failed because of the new rocket's higher speed.

For a slightly more detailed (and very interesting) description of "the little bug that could," visit http://www.around.com/ariane.html .


Impact

Code that was not designed to work in production and that has not been verified to work properly in the production environment could accidentally be run in production and create serious problems.

The Ariane 5 rocket blew up 37 seconds after takeoff on its maiden flight because a piece of code that was used only while the rocket was on the ground was left running for the first 40 seconds of flight. This code tried to assign a 64-bit number representing the sideways velocity of the rocket to a 16-bit field—an operation that convinced the rocket's navigation computer that it was going the wrong way. (See the sidebar on Ariane on page 218 for more details.) While we believe the Test Hook would never be exercised in production, do we really want to take this kind of chance?

Root Cause

In some cases, the Test Logic in Production is introduced to make the behavior of the SUT more deterministic by returning known (hard-coded) values. In other cases, the Test Logic in Production may have been introduced to avoid executing code that cannot be run in a test environment. Unfortunately, this approach can result in failure to execute that code in the production environment if something is misconfigured.

In some cases, tests may require that the SUT execute additional code that would otherwise be executed by a depended-on component. For example, code run from a trigger in a database will not run if the database is replaced by a Fake Database (see Fake Object on page 551 ); thus the test needs to ensure that the equivalent logic is executed from somewhere within the SUT.

Possible Solution

Instead of adding test logic into the production code directly, we can move logic into a substitutable dependency. We can put code that should be run in only production into a Strategy [GOF] object that is installed by default and replaced by a Null Object [PLOPD3] when running our tests. In contrast, code that should be run only during tests can be put into a Strategy [GOF] object that is configured as a Null Object by default. Then, when we want the SUT to execute extra code during testing, we can replace this Strategy object with a test-specific version. To ensure this mechanism is configured properly, we should have a Constructor Test (see Test Method on page 348 ) to verify that any variables holding references to Strategy objects are initialized correctly when they are not overridden by the test.

It may also be possible to override specific methods of the SUT in a Test-Specific Subclass (page 579 ) if the production logic we want to circumvent is localized in overridable methods. This ability is enabled by Self-Calls [WWW] .

Cause: For Tests Only

Code exists in the SUT strictly for use by tests.

Symptoms

Some of the methods of the SUT are used only by tests. Some of the attributes are public when they really should be private.

Impact

Software that is added to the SUT For Tests Only makes the SUT more complex. It can confuse potential clients of the software's interface by introducing additional methods that should not be used by any code other than the tests. These methods may have been tested only in very specific circumstances, so they might not work in the typical usage patterns used by real client software.

Root Cause

The test automater may need to add methods to a class that expose information needed by the test or methods that provide greater control over initialization (such as for the installation of a Test Double ; see page 522 ). Test-driven development will lead to the creation of these additional methods even though they aren't really needed by clients. When retrofitting tests onto legacy code, the test automater may need access to information or functionality that is not already exposed.

For Tests Only can also result when a SUT is used asymmetrically in real life. Automated tests (especially round-trip tests) typically use software in a more symmetric fashion and hence may need methods that the real software clients do not need.

Possible Solution

We can assure that tests have access to private information by creating a Test-Specific Subclass of the SUT, which then provides methods to expose the needed attributes or initialization logic. A test needs to be able to create instances of the subclass instead of the SUT class for this approach to work.

If for some reason the extra methods cannot be moved to a Test-Specific Subclass , they should be clearly labeled For Tests Only . This can be done by adopting a naming convention such as starting the names with "FTO_".

Cause: Test Dependency in Production

Production executables depend on test executables.

Symptoms

We cannot build only the production code; some test code must be included in the build to allow the production code to compile. Alternatively, we might notice that we cannot run the production code if the test executables are not present.

Impact

Even if the production modules do not contain any test code, problems can arise if any of these modules depends on a test module. At minimum, this dependency increases the size of the executable even if none of the test code is actually used in production scenarios. It also opens the door to accidental execution of test code during production.

Root Cause

Test Dependency in Production is usually caused by a lack of attention to inter-module dependencies. It may also arise when a built-in self-test requires access to parts of the test automation infrastructure, such as Test Utility Methods (page 599 ) or the Test Automation Framework (page 298 ), to report test results.

Possible Solution

We must manage our dependencies carefully to ensure that no production code depends on test code even for innocuous things such as type definitions.

Anything required by both test and production code should live in a production module or class that is accessible to both.

Cause: Equality Pollution

Another cause of Test Logic in Production is the implementation of test-specific equality in the equals method of the SUT.

Symptoms

Equality Pollution can be difficult to spot once it has occurred—what is notable is that the SUT doesn't actually need the equals method to be implemented. In other cases, behavioral symptoms may appear, such as test failure when the equals method is modified to support the specific needs of a test or when the definition of equals changes within the SUT as part of a new feature or user story.

Impact

We may write unnecessary equals methods simply to satisfy tests. We may also change the definition of equals so that it no longer satisfies the business requirements.

Equality Pollution may make it difficult to introduce the equals logic prescribed by some new requirement if it already exists to support test-specific equality for another test.

Root Cause

Equality Pollution is caused by a lack of awareness of the concept of test-specific equality. Some early versions of dynamic Mock Object (page 544 ) generation tools forced us to use the SUT's definition of equals , which led to Equality Pollution .

Possible Solution

When a test requires test-specific equality, we should use a Custom Assertion (page 474 ) instead of modifying the equals method just so that we can use a built-in Equality Assertion (see Assertion Method on page 362 ).

When using dynamic Mock Object generation tools, we should use a Comparator [WWW] rather than relying on the equals method supplied by the SUT. We can also implement the equals method on a Test-Specific Subclass of an Expected Object (see State Verification on page 462 ) to avoid adding it to a production class directly.

Further Reading

For Tests Only and Equality Pollution were first introduced in a paper at XP2001 called "Refactoring Test Code" [RTC] .