Result Verification Patterns

Patterns in This Chapter

Verification Strategy

       State Verification 462

       Behavior Verification 468

Assertion Method Styles

       Custom Assertion 474

       Delta Assertion 485

       Guard Assertion 490

       Unfinished Test Assertion 494

State Verification

Also known as

State-Based Testing

How do we make tests self-checking when there is state to be verified?

We inspect the state of the system under test after it has been exercised and compare it to the expected state.

image

A Self-Checking Test (see page 26 ) must verify that the expected outcome has occurred without manual intervention by whoever is running the test. But what do we mean by "expected outcome"? The SUT may or may not be "stateful"; if it is stateful, it may or may not have a different state after it has been exercised. As test automaters, it is our job to determine whether our expected outcome is a change of final state or whether we need to be more specific about what occurs while the SUT is being exercised.

State Verification involves inspecting the state of the SUT after it has been exercised.

How It Works

We exercise the SUT by invoking the methods of interest. Then, as a separate step, we interact with the SUT to retrieve its post-exercise state and compare it with the expected end state by calling Assertion Methods (page 362 ).

Normally, we can access the state of the SUT simply by calling methods or functions that return its state. This is especially true when we are doing test-driven development because the tests will have ensured that the state is easily accessible. When we are retrofitting tests, however, we may find it more challenging to access the relevant state information. In these cases, we may need to use a Test-Specific Subclass (page 579 ) or some other technique to expose the state without introducing Test Logic in Production (page 217 ).

A related question is "Where is the state of the SUT stored?" Sometimes, the state is stored within the actual SUT; in other cases, the state may be stored in another component such as a database. In the latter case, State Verification may involve accessing the state within the other component (essentially a layer-crossing test). By contrast, Behavior Verification (page 468 ) would involve verifying the interactions between the SUT and the other component.

When to Use It

We should use State Verification when we care about only the end state of the SUT—not how the SUT got there. Taking such a limited view helps us maintain encapsulation of the implementation of the SUT.

State Verification comes naturally when we are building the software inside out. That is, we build the innermost objects first and then build the next layer of objects on top of them. Of course, we may need to use Test Stubs (page 529 ) to control the indirect inputs of the SUT to avoid Production Bugs (page 268 ) caused by untested code paths. Even then, we are choosing not to verify the indirect outputs of the SUT.

When we do care about the side effects of exercising the SUT that are not visible in its end state (its indirect outputs), we can use Behavior Verification to observe the behavior directly. We must be careful, however, not to create Fragile Tests (page 239 ) by overspecifying the software.

Implementation Notes

There are two basic styles of implementing State Verification .

Variation: Procedural State Verification

When doing Procedural State Verification , we simply write a series of calls to Assertion Methods that pick apart the state information into pieces and compare those bits of information to individual expected values. Most people who are new to automating tests take such a "path of least resistance." The major disadvantage of this approach is that it can result in Obscure Tests (page 186 ) owing to the number of assertions it may take to specify the expected outcome. When the same sequence of assertions must be carried out in many tests or many times within a single Test Method (page 348 ), we also have Test Code Duplication (page 213 ).

Variation: Expected State Specification

Also known as

Expected Object

When doing Expected State Specification , we construct a specification for the post-exercise state of the SUT in the form of one or more objects populated with the expected attributes. We then compare the actual state directly with these objects using a single call to an Equality Assertion (see Assertion Method ). This tends to result in more concise and readable tests. We can use an Expected State Specification whenever we need to verify several attributes and it is possible to construct an object that looks like the object we expect the SUT to return. The more attributes we have that need to be compared and the more tests that need to compare them, the more compelling the argument for using an Expected State Specification . In the most extreme cases, when we have a lot of data to verify, we can construct an "expected table" and verify that the SUT contains it. Fit's "row fixtures" offer a good way to do this in customer tests; tools such as DbUnit are a good way to use Back Door Manipulation (page 327 ) for this purpose.

When constructing the Expected State Specification , we may prefer to use a Parameterized Creation Method (see Creation Method on page 415 ) so that the reader is not distracted by all the necessary but unimportant attributes of the Expected State Specification . The Expected State Specification is most often an instance of the same class that we expect to get back from the SUT. We may have difficulty using an Expected State Specification if the object doesn't implement equality in a way that involves comparing the values of attributes (e.g., by comparing the object references with each other) or if our test-specific definition of equality differs from that implemented by the equals method.

In these cases, we can still use an Expected State Specification if we create a Custom Assertion (page 474 ) that implements test-specific equality. Alternatively, we can build the Expected State Specification from a class that implements our test-specific equality. This class can either be a Test-Specific Subclass that overrides the equals method or a simple Data Transfer Object [CJ2EEP] that implements equals(TheRealObjectClass  other) . Both of these measures are preferable to modifying (or introducing) the equals method on the production class, as that would be a form of Equality Pollution (see Test Logic in Production ). When the class is difficult to instantiate, we can define a Fake Object (page 551 ) that has the necessary attributes plus an equals method that implements test-specific equality. These last few "tricks" are made possible by the fact that Equality Assertions usually ask the Expected State Specification to compare itself to the actual result, rather than the reverse.

We can build the Expected State Specification either during the result verification phase of the test immediately before it is used in the Equality Assertion or during the fixture setup phase of the test. The latter strategy allows us to use attributes of the Expected State Specification as parameters passed to the SUT or as the base for Derived Values (page 718 ) when building other objects in the test fixture. This makes it easier to see the cause–effect relationship between the fixture and the Expected State Specification, which in turn helps us achieve Tests as Documentation (see page 23 ). It is particularly useful when the Expected State Specification is created out of sight of the test reader such as when using Creation Methods to do the construction.

Motivating Example

This simple 1 example features a test that exercises the code that adds a line item to an invoice. Because it contains no assertions, it is not a Self-Checking Test .

      public  void  testInvoice_addOneLineItem_quantity1()  {
            //  Exercise
            inv.addItemQuantity(product,  QUANTITY);
      }

We have chosen to create the invoice and product in the setUp method, an approach called Implicit Setup (page 424 ).

    public  void  setUp()  {
          product  =  createAnonProduct();
          anotherProduct  =  createAnonProduct();
          inv  =  createAnonInvoice();
    }

Refactoring Notes

The first refactoring we can do is not really a refactoring at all, because we are changing the behavior of the tests (for the better): We introduce some assertions that specify the expected outcome. This results in an example of Procedural State Verification because we make this change within the Test Method as a series of calls to built-in Assertion Methods .

We can further simplify the Test Method by refactoring it to use an Expected Object . First, we build an Expected Object by constructing an object of the expected class, or a suitable Test Double (page 522 ), and initializing it with the values that were previously specified in the assertions. Then we replace the series of assertions with a single Equality Assertion that compares the actual result with an Expected Object . We may have to use a Custom Assertion if we need test-specific equality.

Example: Procedural State Verification

Here we have added the assertions to the Test Method to turn it into a Self-Checking Test . Because several steps must be carried out to verify the expected outcome, this test suffers from a mild case of Obscure Test .

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

Example: Expected Object

In this simplified version of the test, we use the Expected Object with a single Equality Assertion instead of a series of assertions on individual attributes:

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

Because we are also using some of the attributes as arguments of the SUT, we have chosen to build the Expected Object during the fixture setup phase of the test and to use the attributes of the Expected Object as the SUT arguments.

Behavior Verification

Also known as

Interaction Testing

How do we make tests self-checking when there is no state to verify?

We capture the indirect outputs of the SUT as they occur and compare them to the expected behavior.

image

A Self-Checking Test (see page 26 ) must verify that the expected outcome has occurred without manual intervention by whoever is running the test. But what do we mean by "expected outcome"? The SUT may or may not be "stateful"; if it is stateful, it may or may not be expected to end up in a different state after it has been exercised. The SUT may also be expected to invoke methods on other objects or components.

Behavior Verification involves verifying the indirect outputs of the SUT as it is being exercised.

How It Works

Each test specifies not only how the client of the SUT interacts with it during the exercise SUT phase of the test, but also how the SUT interacts with the components on which it should depend. This ensures that the SUT really is behaving as specified rather than just ending up in the correct post-exercise state.

Behavior Verification almost always involves interacting with or replacing a depended-on component (DOC) with which the SUT interacts at runtime. The line between Behavior Verification and State Verification (page 462 ) can get a bit blurry when the SUT stores its state in the DOC because both forms of verification involve layer-crossing tests. We can distinguish between the two cases based on whether we are verifying the post-test state in the DOC ( State Verification ) or whether we are verifying the method calls made by the SUT on the DOC ( Behavior Verification ).

When to Use It

Behavior Verification is primarily a technique for unit tests and component tests. We can use Behavior Verification whenever the SUT calls methods on other objects or components. We must use Behavior Verification whenever the expected outputs of the SUT are transient and cannot be determined simply by looking at the post-exercise state of the SUT or the DOC. This forces us to monitor these indirect outputs as they occur.

A common application of Behavior Verification is when we are writing our code in an "outside-in" manner. This approach, which is often called need-driven development, involves writing the client code before we write the DOC. It is a good way to find out exactly what the interface provided by the DOC needs to be based on real, concrete examples rather than on speculation. The main objection to this approach is that we need to use a lot of Test Doubles (page 522 ) to write these tests. That could result in Fragile Tests (page 239 ) because each test knows so much about how the SUT is implemented. Because the tests specify the behavior of the SUT in terms of its interactions with the DOC, a change in the implementation of the SUT could break a lot of tests. This kind of Overspecified Software (see Fragile Test ) could lead to High Test Maintenance Cost (page 265 ).

The jury is still out on whether Behavior Verification is a better approach than State Verification . In most cases, State Verification is clearly necessary; in some cases, Behavior Verification is clearly necessary. What has yet to be determined is whether Behavior Verification should be used in all cases or whether we should use State Verification most of the time and resort to Behavior Verification only when State Verification falls short of full test coverage.

Implementation Notes

Before we exercise the SUT by invoking the methods of interest, we must ensure that we have a way of observing its behavior. Sometimes the mechanisms that the SUT uses to interact with the components surrounding it make such observation possible; when this is not the case, we must install some sort of Test Double to monitor the SUT's indirect outputs. We can use a Test Double as long as we have a way to replace the DOC with the Test Double . This could be via Dependency Injection (page 678 ) or by Dependency Lookup (page 686 ).

There are two fundamentally different ways to implement Behavior Verification , each with its own proponents. The Mock Object (page 544 ) community has been very vocal about the use of "mocks" as an Expected Behavior Specification, so it is the more commonly used approach. Nevertheless, Mock Objects are not the only way of doing Behavior Verification .

Variation: Procedural Behavior Verification

In Procedural Behavior Verification , we capture the method calls made by the SUT as it executes and later get access to them from within the Test Method (page 348 ). Then we use Equality Assertions (see Assertion Method on page 362 ) to compare them with the expected results.

Also known as

Expected Behavior

The most common way of trapping the indirect outputs of the SUT is to install a Test Spy (page 538 ) in place of the DOC during the fixture setup phase of the Four-Phase Test (page 358 ). During the result verification phase of the test, we ask the Test Spy how it was used by the SUT during the exercise SUT phase. Use of a Test Spy does not require any advance knowledge of how the methods of the DOC will be called.

The alternative is to ask the real DOC how it was used. Although this scheme is not always feasible, when it is, it avoids the need to use a Test Double and minimizes the degree to which we have Overspecified Software .

We can reduce the amount of code in the Test Method (and avoid Test Code Duplication ; see page 213 ) by defining Expected Objects (see State Verification ) for the arguments of method calls or by delegating the verification of them to Custom Assertions (page 474 ).

Variation: Expected Behavior Specification

Expected Behavior Specification is a different way of doing Behavior Verification . Instead of waiting until after the fact to verify the indirect outputs of the SUT by using a sequence of assertions, we load the Expected Behavior Specification into a Mock Object and let it verify that the method calls are correct as they are received.

We can use an Expected Behavior Specification when we know exactly what should happen ahead of time and we want to remove all Procedural Behavior Verification from the Test Method . This pattern variation tends to make the test shorter (assuming we are using a compact representation of the expected behavior) and can be used to cause the test to fail on the first deviation from the expected behavior if we so choose.

One distinct advantage of using Mock Objects is that Test Double generation tools are available for many members of the xUnit family. They make implementing Expected Behavior Specification very easy because we don't need to manually build a Test Double for each set of tests. One drawback of using a Mock Object is that it requires that we can predict how the methods of the DOC will be called and what arguments will be passed to it in the method calls.

Motivating Example

The following test is not a Self-Checking Test because it does not verify that the expected outcome has actually occurred; it contains no calls to Assertion Methods, nor does it set up any expectations on a Mock Object . Because we are testing the logging functionality of the SUT, the state that interests us is actually stored in the logger rather than within the SUT itself. The writer of this test hasn't found a way to access the state we are trying to verify.

      public  void  testRemoveFlightLogging_NSC()  throws  Exception  {
            //  setup
            FlightDto  expectedFlightDto  =  createARegisteredFlight();
            FlightManagementFacade  facade  =
                      new  FlightManagementFacadeImpl();
            //  exercise
            facade.removeFlight(expectedFlightDto.getFlightNumber());
            //  verify
            //  have  not  found  a  way  to  verify  the  outcome  yet
            //    Log  contains  record  of  Flight  removal
      }

To verify the outcome, whoever is running the tests must access the database and the log console and compare what was actually output to what should have been output.

One way to make the test Self-Checking is to enhance the test with Expected State Specification (see State Verification ) of the SUT as follows:

      public  void  testRemoveFlightLogging_ESS()  throws  Exception  {
            //  fixture  setup
            FlightDto  expectedFlightDto  =  createAnUnregFlight();
            FlightManagementFacadeImplTI  facade  =
                      new  FlightManagementFacadeImplTI();
            //  exercise
            facade.removeFlight(expectedFlightDto.getFlightNumber());
            //  verify
            assertFalse("flight  still  exists  after  being  removed",
                                facade.flightExists(  expectedFlightDto.
                                                                                  getFlightNumber()));
      }

Unfortunately, this test does not verify the logging function of the SUT in any way. It also illustrates one reason why Behavior Verification came about: Some functionality of the SUT is not visible within the end state of the SUT itself, but can be seen only if we intercept the behavior at an internal observation point between the SUT and the DOC or if we express the behavior in terms of state changes for the objects with which the SUT interacts.

Refactoring Notes

When we made the changes in the second code sample in the "Motivating Example," we weren't really refactoring; instead, we added verification logic to make the tests behave differently. There are, however, several refactoring cases that are worth discussing.

To refactor from State Verification to Behavior Verification, we must do a Replace Dependency with Test Double (page 522 ) refactoring to gain visibility of the indirect outputs of the SUT via a Test Spy or Mock Object .

To refactor from an Expected Behavior Specification to Procedural Behavior Verification , we install a Test Spy instead of the Mock Object. After exercising the SUT, we make assertions on values returned by the Test Spy and compare them with the expected values that were originally used as arguments when we initially configured the Mock Object (the one that we just converted into a Test Spy ).

To refactor from Procedural Behavior Verification to an Expected Behavior Specification, we configure a Mock Object with the expected values from the assertions made on values returned by the Test Spy and install the Mock Object instead of the Test Spy .

Example: Procedural Behavior Verification

The following test verifies the basic functionality of creating a flight but uses Procedural Behavior Verification to verify the indirect outputs of the SUT. That is, it uses a Test Spy to capture the indirect outputs and then verifies those outputs are correct by making in-line calls to the Assertion Methods .

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

Example: Expected Behavior Specification

In this version of the test, we use the JMock framework to define the expected behavior of the SUT. The method expects on mockLog configures the Mock Object with the Expected Behavior Specification (specifically, the expected log message).

      public  void  testRemoveFlight_JMock()  throws  Exception  {
            //  fixture  setup
            FlightDto  expectedFlightDto  =  createAnonRegFlight();
            FlightManagementFacade  facade  =
                      new  FlightManagementFacadeImpl();
            //  mock  configuration
            Mock  mockLog  =  mock(AuditLog.class);
            mockLog.expects(once()).method("logMessage")
                              .with(eq(helper.getTodaysDateWithoutTime()),
                                       eq(Helper.TEST_USER_NAME),
                                       eq(Helper.REMOVE_FLIGHT_ACTION_CODE),
                                       eq(expectedFlightDto.getFlightNumber()));
         //  mock  installation
            facade.setAuditLog((AuditLog)  mockLog.proxy());
            //  exercise
            facade.removeFlight(expectedFlightDto.getFlightNumber());
            //  verify
            //  verify()  method  called  automatically  by  JMock
      }

Custom Assertion

Also known as

Bespoke Assertion

How do we make tests self-checking when we have test-specific equality logic?
How do we reduce Test Code Duplication when the same assertion logic appears in many tests?
How do we avoid Conditional Test Logic?

We create a purpose-built Assertion Method that compares only those attributes of the object that define test-specific equality.

image

Most members of the xUnit family provide a reasonably rich set of Assertion Methods (page 362 ). But sooner or later, we inevitably find ourselves saying, "This test would be so much easier to write if I just had an assertion that did . . . ." So why not write it ourselves?

The reasons for writing a Custom Assertion are many, but the technique is pretty much the same regardless of our goal. We hide the complexity of whatever it takes to prove the system is behaving correctly behind an Assertion Method with an Intent-Revealing Name [SBPP] .

How It Works

We encapsulate the mechanics of verifying that something is true (an assertion) behind an Intent-Revealing Name. To do so, we factor out all the common assertion code within the tests into a Custom Assertion that implements the verification logic. A Custom Equality Assertion takes two parameters: an Expected Object (see State Verification on page 462 ) and the actual object.

A key characteristic of Custom Assertions is that they receive everything they need to pass or fail the test as parameters. Other than causing the test to fail, they have no side effects.

Typically, we create Custom Assertions through refactoring by identifying common patterns of assertions in our tests. When test driving, we might just go ahead and call a nonexistent Custom Assertion because it makes writing our test easier; this tactic lets us focus on the part of the SUT that needs to be tested rather than the mechanics of how the test would be carried out.

When to Use It

We should consider creating a Custom Assertion whenever any of the following statements are true:

  • We find ourselves writing (or cloning) the same assertion logic in test after test ( Test Code Duplication; see page 213 ).
  • We find ourselves writing Conditional Test Logic (page 200 ) in the result verification part of our tests. That is, our calls to Assertion Methods are embedded in if statements or loops.
  • The result verification parts of our tests suffer from Obscure Test (page 186 ) because we use procedural rather than declarative result verification in the tests.
  • We find ourselves doing Frequent Debugging (page 248 ) whenever assertions fail because they do not provide enough information.

A key reason for moving the assertion logic out of the tests and into Custom Assertions is to Minimize Untestable Code (see page 44 ). Once the verification logic has been moved into a Custom Assertion , we can write Custom Assertion Tests (see Custom Assertion on page 474 ) to prove the verification logic is working properly. Another important benefit of using Custom Assertions is that they help avoid Obscure Tests and make tests Communicate Intent (see page 41 ). That, in turn, will help produce robust, easily maintained tests.

If the verification logic must interact with the SUT to determine the actual outcome, we can use a Verification Method (see Custom Assertion ) instead of a Custom Assertion . If the setup and exercise parts of the tests are also the same except for the values of the actual/expected objects, we should consider using a Parameterized Test (page 607 ). The primary advantage of Custom Assertions over both of these techniques is reusability; the same Custom Assertion can be reused in many different circumstances because it is independent of its context (its only contact with the outside world occurs through its parameter list).

We most commonly write Custom Assertions that are Equality Assertions (see Assertion Method ), but there is no reason why we cannot write other kinds as well.

Variation: Custom Equality Assertion

For custom equality assertions, the Custom Assertion must be passed an Expected Object and the actual object to be verified. It should also take an Assertion Message (page 370 ) to avoid playing Assertion Roulette (page 224 ). Such an assertion is essentially an equals method implemented as a Foreign Method [Fowler].

Variation: Object Attribute Equality Assertion

We often run across Custom Assertions that take one actual object and several different Expected Objects that need to be compared with specific attributes of the actual object. (The set of attributes to be compared is implied by the name of the Custom Assertion .) The key difference between these Custom Assertions and a Verification Method is that the latter interacts with the SUT while the Object Attribute Equality Assertion looks only at the objects passed in as parameters.

Variation: Domain Assertion

All of the built-in Assertion Methods are domain independent. Custom Equality Assertions implement test-specific equality but still compare only two objects. Another style of Custom Assertion helps contribute to the definition of a "domain-specific" Higher-Level Language (see page 41 )—namely, the Domain Assertion .

A Domain Assertion is a Stated Outcome Assertion (see Assertion Method ) that states something that should be true in domain-specific terms. It helps elevate the test into "business-speak."

Variation: Diagnostic Assertion

Sometimes we find ourselves doing Frequent Debugging whenever a test fails because the assertions tell us only that something is wrong but do not identify the specific problem (e.g., the assertions indicate these two objects are not equal but it isn't clear what isn't equal about the object). We can write a special kind of Custom Assertion that may look just like one of the built-in assertions but provide more information about what is different between the expected and actual values than a built-in assertion because it is specific to our types. (For example, it might tell us which attributes are different or where long strings differ.)

On one project, we were comparing string variables containing XML. Whenever a test failed, we had to bring up two string inspectors and scroll through them looking for the difference. Finally, we got smart and included the logic in a Custom Assertion that told us where the first difference between the two XML strings occurred. The small amount of time we spent writing the diagnostic custom assertion was paid back many times over as we ran our tests.

Variation: Verification Method

In customer tests, a lot of the complexity of verifying the outcome is related to interacting with the SUT. Verification Methods are a form of Custom Assertions that interact directly with the SUT, thereby relieving their callers from this task. This simplifies the tests significantly and leads to a more "declarative" style of outcome specification. After the Custom Assertion has been written, we can write subsequent tests that result in the same outcome much more quickly. In some cases, it may be advantageous to incorporate even the exercise SUT phase of the test into the Verification Method . This is one step short of a full Parameterized Test that incorporates all the test logic in a reusable Test Utility Method (page 599 ).

Implementation Notes

The Custom Assertion is typically implemented as a set of calls to the various built-in Assertion Methods . Depending on how we plan to use it in our tests, we may also want to include the standard Equality Assertion template to ensure correct behavior with null parameters. Because the Custom Assertion is itself an Assertion Method , it should not have any side effects, nor should it call the SUT. (If it needs to do so, it would be a Verification Method .)

Variation: Custom Assertion Test

Testing zealots would also write a Custom Assertion Test (a Self-Checking Test —see page 26 —for Custom Assertions ) to verify the Custom Assertion . The benefit from doing so is obvious: increased confidence in our tests. In most cases, writing Custom Assertion Tests isn't particularly difficult because Assertion Methods take all their arguments as parameters.

We can treat the Custom Assertion as the SUT simply by calling it with various arguments and verifying that it fails in the right cases. Single-Outcome Assertions (see Assertion Method ) need only a single test because they don't take any parameters (other than possibly an Assertion Message ). Stated Outcome Assertions need one test for each possible value (or boundary value). Equality Assertions need one test that compares two objects deemed to be equivalent, one test that compares an object with itself, and one test for each attribute whose inequality should cause the assertion to fail. Attributes that don't affect equality can be verified in one additional test because the Equality Assertion should not raise an error for any of them.

The Custom Assertions follow the normal Simple Success Test (see Test Method on page 348 ) and Expected Exception Test (see Test Method ) templates with one minor difference: Because the Assertion Method is the SUT, the exercise SUT and verify outcome phases of the Four-Phase Test (page 358 ) are combined into a single phase.

Each test consists of setting up the Expected Object and the actual object and then calling the Custom Assertion . If the objects should be equivalent, that's all there is to it. (The Test Automation Framework described on page 298 would catch any assertion failures and fail the test.) For the tests where we expect the Custom Assertion to fail, we can write the test as an Expected Exception Test (except that the exercise SUT and verify outcome phases of the Four-Phase Test are combined into the single call to the Custom Assertion ).

The simplest way to build the objects to be compared for a specific test is to do something similar to One Bad Attribute (see Derived Value on page 718 )—that is, build the first object and make a deep copy of it. For successful tests, modify any of the attributes that should not be compared. For each test failure, modify one attribute that should be grounds for failing the assertion.

A brief warning about a possible complication in a few members of the xUnit family: If all of the test failure handling does not occur in the Test Runner (page 377 ), calls to fail or built-in assertions may add messages to the failure log even if we catch the error or exception in our Custom Assertion Test . The only way to circumvent this behavior is to use an "Encapsulated Test Runner" to run each test by itself and verify that the one test failed with the expected error message.

Motivating Example

In the following example, several test methods repeat the same series of assertions:

    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()  {
          //  Setup
          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());
    }
    //
    //      Adding  TWO  line  items
    //

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

Note that the first test ends with a series of three assertions and the second test repeats the series of three assertions twice, once for each line item. This is clearly a bad case of Test Code Duplication .

Refactoring Notes

Refactoring zealots can probably see that the solution is to do an Extract Method [Fowler] refactoring on these tests. If we pull out all the common calls to Assertion Methods, we will be left with only the differences in each test. The extracted method is our Custom Assertion . We may also need to introduce an Expected Object to hold all the values that were being passed to the individual Assertion Methods on a single object to be passed to the Custom Assertion .

Example: Custom Assertion

In this test, we use a Custom Assertion to verify that LineItem matches the expected LineItem (s). For one reason or another, we have chosen to implement a test-specific equality rather than using a standard Equality Assertion .

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

    public  void  testAddItemQuantity_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);
          assertLineItemsEqual("Item  1",expItem1,actual);
          //  Verify  second  item
          actual  =  (LineItem)lineItems.get(1);
          assertLineItemsEqual("Item  2",expItem2,  actual);
    }

The tests have become significantly smaller and more intent-revealing. We have also chosen to pass a string indicating which item we are examining as an argument to the Custom Assertion to avoid playing Assertion Roulette when a test fails.

This simplified test was made possible by having the following Custom Assertion available to us:

    static  void  assertLineItemsEqual(
                               String    msg,  LineItem  exp,  LineItem  act)  {
          assertEquals(msg+"  Inv",    exp.getInv(),act.getInv());
          assertEquals(msg+"  Prod",  exp.getProd(),  act.getProd());
          assertEquals(msg+"  Quan",  exp.getQuantity(),  act.getQuantity());
    }

This Custom Assertion compares the same attributes of the object as we were comparing on an in-line basis in the previous version of the test; thus the semantics of the test haven't changed. We also concatenate the name of the attribute being compared with the message parameter to get a unique failure message, which allows us to avoid playing Assertion Roulette when a test fails.

Example: Domain Assertion

In this next version of the test, we have further elevated the level of the assertions to better communicate the expected outcome of the test scenarios:

    public  void  testAddOneLineItem_quantity1()  {
          Invoice  inv  =  createAnonInvoice();
          LineItem  expItem  =  new  LineItem(inv,  product,  QUANTITY);
          //  Exercise
          inv.addItemQuantity(  product,  QUANTITY);
          //  Verify
          assertInvoiceContainsOnlyThisLineItem(  inv,  expItem);
    }

    public  void  testRemoveLineItemsForProduct_oneOfTwo_()  {
          Invoice  inv  =  createAnonInvoice();
          inv.addItemQuantity(  product,  QUANTITY);
          inv.addItemQuantity(  anotherProduct,  QUANTITY);
          LineItem  expItem  =  new  LineItem(  inv,  product,  QUANTITY);
          //  Exercise
          inv.removeLineItemForProduct(  anotherProduct  );
          //  Verify
          assertInvoiceContainsOnlyThisLineItem(  inv,  expItem);
    }

This simplified version of the test was made possible by extracting the following Domain Assertion method:

    void  assertInvoiceContainsOnlyThisLineItem(
                                                         Invoice  inv,
                                                         LineItem  expItem)  {
          List  lineItems  =  inv.getLineItems();
          assertEquals("number  of  items",  lineItems.size(),  1);
          LineItem  actual  =  (LineItem)lineItems.get(0);
          assertLineItemsEqual("item",expItem,  actual);
    }

This example chose to forgo passing a message to the Domain Assertion to save a bit of space. In real life, we would typically include a message string in the parameter list and concatenate the messages of the individual assertions to one passed in. See Assertion Message (page 370 ) for more details.

Example: Verification Method

If the exercise SUT and result verification phases of several tests are pretty much identical, we can incorporate both phases into our reusable Custom Assertion . Because this approach changes the semantics of the Custom Assertion from being just a function free of side effects to an operation that changes the state of the SUT, we usually give it a more distinctive name starting with "verify".

This version of the test merely sets up the test fixture before calling a Verification Method that incorporates both the exercise SUT and verify outcome phases of the test. It is most easily recognized by the lack of a distinct "exercise" phase in the calling test and the presence of calls to methods that modify the state of one of the objects passed as a parameter of the Verification Method .

    public  void  testAddOneLineItem_quantity2()  {
          Invoice  inv  =  createAnonInvoice();
          LineItem  expItem  =  new  LineItem(inv,  product,  QUANTITY);
          //  Exercise  &  Verify
          verifyOneLineItemCanBeAdded(inv,  product,  QUANTITY,  expItem);
    }

The Verification Method for this example looks like this:

    public  void  verifyOneLineItemCanBeAdded(
                          Invoice  inv,  Product  product,
                         int  QUANTITY,  LineItem  expItem)  {
          //  Exercise
          inv.addItemQuantity(product,  QUANTITY);
          //  Verify
          assertInvoiceContainsOnlyThisLineItem(inv,  expItem);
    }

This Verification Method calls the "pure" Custom Assertion , although it could just as easily have included all the assertion logic if we didn't have the other Custom Assertion to call. Note the call to addItemQuantity on the parameter inv ; this is what changes if from a Custom Assertion to a Verification Method .

Example: Custom Assertion Test

This Custom Assertion isn't particularly complicated, so we may feel comfortable without having any automated tests for it. If there is anything complex about it, however, we may find it worthwhile to write tests like these:

    public  void  testassertLineItemsEqual_equivalent()  {
          Invoice  inv  =  createAnonInvoice();
          LineItem  item1  =  new  LineItem(inv,  product,  QUANTITY1);
          LineItem  item2  =  new  LineItem(inv,  product,  QUANTITY1);
          //  exercise/verify
          assertLineItemsEqual("This  should  not  fail",item1,  item2);
    }

    public  void  testassertLineItemsEqual_differentInvoice()  {
          Invoice  inv1  =  createAnonInvoice();
          Invoice  inv2  =  createAnonInvoice();
          LineItem  item1  =  new  LineItem(inv1,  product,  QUANTITY1);
          LineItem  item2  =  new  LineItem(inv2,  product,  QUANTITY1);
          //  exercise/verify
          try  {
                assertLineItemsEqual("Msg",item1,  item2);
          }  catch  (AssertionFailedError  e)  {
                assertEquals("e.getMsg",
                                          "Invoice-expected:  <123>  but  was  <124>",
                                 e.getMessage());
       return;
          }
          fail("Should  have  thrown  exception");
    }

    public  void  testassertLineItemsEqual_differentQuantity()  {
          Invoice  inv  =  createAnonInvoice();
          LineItem  item1  =  new  LineItem(inv,  product,  QUANTITY1);
          LineItem  item2  =  new  LineItem(inv,  product,  QUANTITY2);
          //  exercise/verify
          try  {
                assertLineItemsEqual("Msg",item1,  item2);
          }  catch  (AssertionFailedError  e)  {
                pass();    //  to  indicate  that  no  assertion  is  needed
                return;
          }
          fail("Should  have  thrown  exception");
    }

This example includes a few of the Custom Assertion Tests needed for this Custom Assertion . Note that the code includes one "equivalent" and several "different" tests (one for each attribute whose difference should cause the test to fail). We have to use the second form of the Expected Exception Test template in those cases where the assertion was expected to fail, because fail throws the same exception as our assertion method. In one of the "different" tests, we have included sample logic for asserting on the exception message. (Although I've abridged it to save space, the example here should give you an idea of where to assert on the message.)

Delta Assertion

How do we make tests self-checking when we cannot control the initial contents of the fixture?

We specify assertions based on differences between the pre- and post-exercise state of the SUT.

image

When we are using a Shared Fixture (page 317 ) such as a test database, it can be challenging to code the assertions that state what the content of the fixture should be after the SUT has been exercised. This is because other tests may have created objects in the fixture that our assertions may detect and that may cause our assertions to fail. One solution is to isolate the current test from all other tests by using a Database Partitioning Scheme (see Database Sandbox on page 650 ). But what can we do if this option is not available to us?

Using Delta Assertions allows us to be less dependent on which data already exist in the Shared Fixture .

How It Works

Before exercising the SUT, we take a snapshot of relevant parts of the Shared Fixture . After exercising the SUT, we specify our assertions relative to the saved snapshot. The Delta Assertions typically verify that the number of objects has changed by the right number and that the contents of collections of objects returned by the SUT in response to our queries have been augmented by the expected objects.

When to Use It

We can use a Delta Assertion whenever we don't have full control over the test fixture and we want to avoid Interacting Tests (see Erratic Test on page 228 ). Using Delta Assertions will help make our tests more resilient to changes in the fixture. We can also use Delta Assertions in concert with Implicit Teardown (page 516 ) to detect memory or data leaks in the code that we are testing. See the sidebar " Using Delta Assertions to Detect Data Leakage " on page 487 for a more detailed description.

Delta Assertions work well when tests are run one after another from the same Test Runner (page 377 ). Unfortunately, they cannot prevent a Test Run War (see Erratic Test ) because such a problem arises when tests are run at the same time from different processes. Delta Assertions work whenever the state of the SUT and the fixture are modified only by our own test. If other tests are running in parallel (not before or after the current test, but at the same time ), a Delta Assertion won't be sufficient to avoid the Test Run War problem.

Implementation Notes

When saving the pre-test state of the Shared Fixture or SUT, we must make sure that the SUT cannot change our snapshot. For example, if our snapshot consists of a collection of objects returned by the SUT in response to a query, we must perform a deep copy; a shallow copy copies only the Collection object and not the objects to which it refers. Shallow copying would allow the SUT to modify the very objects it returned to us as we exercise it; as a consequence, we would lose the reference snapshot with which we are comparing the post-test state.

We can ensure that we have the correct post-test state in several different ways. Assuming that our test adds any new objects it plans to modify, one approach is to first check that the result collection (1) has the right number of items, (2) contains all the pre-test items, and (3) contains the new Expected Objects (see State Verification on page 462 ). Another approach is to remove all the saved items from the result collection and then compare what remains with the collection of new expected objects. Both of these approaches can be hidden behind a Custom Assertion (page 474 ) or a Verification Method (see Custom Assertion ).


Using Delta Assertions to Detect Data Leakage

A long time ago, on a project far away, we were experimenting with different ways to clean up our test fixtures after the customer tests. Our tests were accessing a database and leaving objects behind. This behavior caused all sorts of problems with Unrepeatable Tests (see Erratic Test on page 228 ) and Interacting Tests (see Erratic Test ). We were also suffering from Slow Tests (page 253 ).

Eventually we hit upon the idea of keeping track of all the objects we were creating in our tests by registering them with an Automated Teardown (page 503 ) mechanism. Then we found a way to stub out the database with a Fake Database (see Fake Object on page 551 ). Next we made it possible to run the same test against either the fake database or the real one. This solved many of the interaction problems when running against the fake database, although those problems still occurred when we ran the tests against the real database—tests still left objects behind, and we wanted to know why. But first we had to determine precisely which tests were at fault.

The solution turned out to be pretty simple. In our Fake Database —which was implemented using simple hash tables—we added a method to count the total number of objects. We simply saved this value in an instance variable in the setUp method and used it as the expected value passed to an Equality Assertion (see Assertion Method on page 362 ) called in the tearDown method to verify that we had cleaned up all objects properly. [This is an example of using Delta Assertions (page 485 ).] Once we implemented this little trick, we quickly found out which tests were suffering from the Data Leak (see Erratic Test ). We could then focus our efforts on a much smaller number of tests.

Even today, we find it useful to be able to run the same test against the database and in memory. Similarly, we still occasionally see a test fail when the tearDown method inherited from our company-specific Testcase Superclass (page 638 ) has a Delta Assertion failure. Perhaps the same idea could be applied to checking for memory leaks in programming languages with manual memory management (such as C++).


Motivating Example

The following test retrieves some objects from the SUT. It then compares the objects it actually found with the objects it expected to find.

    public  void  testGetFlightsByOriginAirport_OneOutboundFlight()
                  throws  Exception  {
          FlightDto  expectedFlightDto  =
                createNewFlightBetweenExistingAirports();
          //  Exercise  System
          facade.createFlight(
                            expectedFlightDto.getOriginAirportId(),
                            expectedFlightDto.getDestinationAirportId());
          //  Verify  Outcome
          List  flightsAtOrigin  =  facade.getFlightsByOriginAirport(
                                         expectedFlightDto.getOriginAirportId());
          assertOnly1FlightInDtoList(  "Outbound  flight  at  origin",
                                                      expectedFlightDto,
                                                      flightsAtOrigin);
    }

Unfortunately, because this test used a Shared Fixture , other tests that ran before it may have added objects as well. That behavior could cause the current test to fail if we encounter additional, unexpected objects.

Refactoring Notes

To convert the test to use a Delta Assertion , we must first take a snapshot of the data (or collection of objects) we will later be asserting on. Next, we need to modify our assertions to focus on the difference between the pre-test data/objects and the post-test data/objects. To avoid introducing Conditional Test Logic (page 200 ) into the Test Method (page 348 ), we may want to introduce a new Custom Assertion . Although we may be able to use existing assertions (custom or otherwise) as a starting point, we'll probably have to modify them to take the pre-test data into account.

Example: Delta Assertion

In this version of the test, we use a Delta Assertion to verify the objects added when we exercised the SUT. Here we are verifying that we have one more object than before and that the collection of objects returned by the SUT includes the new Expected Object and all objects that it previously contained.

    public  void  testCreateFlight_Delta()
                  throws  Exception  {
          FlightDto  expectedFlightDto  =
                createNewFlightBetweenExistingAirports();
          //  Remember  prior  state
          List  flightsBeforeCreate  =
                facade.getFlightsByOriginAirport(
                                       expectedFlightDto.getOriginAirportId());
          //  Exercise  system
          facade.createFlight(
                               expectedFlightDto.getOriginAirportId(),
                              expectedFlightDto.getDestinationAirportId());
          //  Verify  outcome  relative  to  prior  state
          List  flightsAfterCreate  =
                facade.getFlightsByOriginAirport(
                                expectedFlightDto.getOriginAirportId());
          assertFlightIncludedInDtoList(  "new  flight  ",
                                                          expectedFlightDto,
                                                          flightsAfterCreate);
          assertAllFlightsIncludedInDtoList(  "previous  flights",
                                                                  flightsBeforeCreate,
                                                                  flightsAfterCreate);
          assertEquals(  "Number  of  flights  after  create",
                             flightsBeforeCreate.size()+1,
                             flightsAfterCreate.size());
    }

Because the SUT returns Data Transfer Objects [CJ2EEP] , we can be assured that the objects we saved before exercising the SUT cannot possibly change. We have modified our Custom Assertions to ignore the pre-test objects (by not insisting that the Expected Object is the only one) and have written a new Custom Assertion that ensures all pre-test objects are also present. Another way to accomplish this task is to remove the pre-test objects from the result collection and then verify that only the new Expected Objects are left.

I've omitted the implementation of the Custom Assertions, as it is purely an exercise in comparing objects and is not salient to understanding the Delta Assertion pattern. The "test infected" among us would, of course, write the Custom Assertions driven by some Custom Assertion Tests (see Custom Assertion ).

Guard Assertion

How do we avoid Conditional Test Logic ?

We replace an if statement in a test with an assertion that fails the test if not satisfied.

image

Some verification logic may fail because information returned by the SUT is not initialized as expected. When a test encounters an unexpected problem, it may produce a test error rather than a test failure. While the Test Runner (page 377 ) does its best to provide useful diagnostic information, the test automater can often do better by checking for the particular condition and reporting it explicitly.

A Guard Assertion is a good way to do so without introducing Conditional Test Logic (page 200 ).

How It Works

Tests either pass or fail. We fail tests by calling Assertion Methods (page 362 ) that stop the test from executing further if the assertion's condition is not met. Alternatively, we can replace Conditional Test Logic that is used to avoid executing assertions when they would cause test errors with assertions that fail the test instead. This pattern also documents the fact that we expect the condition of the Guard Assertion to be true. A failure of the Guard Assertion makes it very clear that some condition we expected to be true was not; it eliminates the effort needed to infer the test result from the conditional logic.

When to Use It

We should use a Guard Assertion whenever we want to avoid executing statements in our Test Method (page 348 ) because they would cause an error if they were executed when some condition related to values returned by the SUT is not true. We take this step instead of putting an if  then  else  fail code construct around the sensitive statements. Normally, a Guard Assertion is placed between the exercise SUT and the verify outcome phases of a Four-Phase Test (page 358 ).

Variation: Shared Fixture State Assertion

When the test uses a Shared Fixture (page 317 ), a Guard Assertion can also be useful at the beginning of the test (before the exercise SUT phase) to verify that the Shared Fixture satisfies the test's needs. It also makes it clearer to the test reader which parts of the Shared Fixture this test actually uses; the greater clarity improves the likelihood of achieving Tests as Documentation (see page 23 ).

Implementation Notes

We can use Stated Outcome Assertions (see Assertion Method ) like assertNotNil and Equality Assertions (see Assertion Method ) like assertEquals as Guard Assertions that fail the test and prevent execution of other statements that would cause test errors.

Motivating Example

Consider the following example:

    public  void  testWithConditionals()  throws  Exception  {
          String  expectedLastname  =  "smith";
          List  foundPeople  =  PeopleFinder.
                    findPeopleWithLastname(expectedLastname);
          if  (foundPeople  !=  null)  {
                if  (foundPeople.size()  ==  1)  {
                      Person  solePerson  =  (Person)  foundPeople.get(0);
                      assertEquals(  expectedLastname,solePerson.getName());
                }  else  {
                      fail("list  should  have  exactly  one  element");
                }
          }  else  {
                fail("list  is  null");
          }
    }

This example includes plenty of conditional statements that the author might get wrong—things like writing (foundPeople  ==  null) instead of (foundPeople  !=  null ). In C-based languages, one might mistakenly use = instead of == , which would result in the test always passing!

Refactoring Notes

We can use a Replace Nested Conditional with Guard Clauses [Fowler] refactoring to transform this spider web of Conditional Test Logic into a nice linear sequence of statements. (In a test, even a single conditional statement is considered too much and hence "nested"!) We can use Stated Outcome Assertions to check for null object references and Equality Assertions to verify the number of objects in the collection. If each assertion is satisfied, the test proceeds. If they are not satisfied, the test ends in failure before it reaches the next statement.

Example: Simple Guard Assertion

This simplified version of the test replaces all conditional statements with assertions. It is shorter than the original test and much easier to read.

    public  void  testWithoutConditionals()  throws  Exception  {
          String  expectedLastname  =  "smith";
          List  foundPeople  =  PeopleFinder.
                    findPeopleWithLastname(expectedLastname);
          assertNotNull("found  people  list",  foundPeople);
          assertEquals(  "number  of  people",  1,  foundPeople.size()  );
          Person  solePerson  =  (Person)  foundPeople.get(0);
          assertEquals(  "last  name",
                           expectedLastname,
                           solePerson.getName()  );
    }

We now have a single linear execution path through this Test Method (page 348 ); it should improve our confidence in the correctness of this test immensely!

Example: Shared Fixture Guard Assertion

Here's an example of a test that depends on a Shared Fixture . If a previous test (or even this test in a previous test run) modifies the state of the fixture, our SUT could return unexpected results. It might take a fair bit of effort to determine that the problem lies in the test's pre-conditions rather than being a bug in the SUT. We can avoid all of this trouble by making the assumptions of this test explicit through the use of a Guard Assertion during the fixture lookup phase of the test.

    public  void  testAddFlightsByFromAirport_OneOutboundFlight_GA()
                  throws  Exception  {
          //  Fixture  Lookup
          List  flights  =  facade.getFlightsByOriginAirport(
                                                 ONE_OUTBOUND_FLIGHT_AIRPORT_ID  );
          //        Guard  Assertion  on  Fixture  Contents
          assertEquals(  "#  flights  precondition",  1,  flights.size());
          FlightDto  firstFlight  =  (FlightDto)  flights.get(0);
          //  Exercise  System
          BigDecimal  flightNum  =  facade.createFlight(
                                                  firstFlight.getOriginAirportId(),
                                                  firstFlight.getDestAirportId());
          //  Verify  Outcome
          FlightDto  expFlight  =  (FlightDto)  firstFlight.clone();
          expFlight.setFlightNumber(  flightNum  );
          List  actual  =  facade.getFlightsByOriginAirport(
                                                   firstFlight.getOriginAirportId());
          assertExactly2FlightsInDtoList(  "Flights  at  origin",
                                                            firstFlight,
                                                            expFlight,
                                                            actual);
    }

We now have a way to determine that the assumptions were violated without extensive debugging! This is another way we achieve Defect Localization (see page 22 ). This time the defect is in the tests' assumptions on the previously run tests' behavior.

Unfinished Test Assertion

How do we structure our test logic to avoid leaving tests unfinished?

We ensure that incomplete tests fail by executing an assertion that is guaranteed to fail.

  void  testSomething()  {
        //  Outline:
              //  create  a  flight  in  ...  state
              //  call  the  ...  method
              //  verify  flight  is  in  ...  state
        fail("Unfinished  Test!");
  }

When we start defining the tests for a particular piece of code, it is useful to "rough in" the tests by defining Test Methods (page 348 ) on the appropriate Testcase Class (page 373 ) as we think of the test conditions. We do, however, want to ensure that we don't accidentally forget to fill in the bodies of these tests if we get distracted. We want the tests to fail until we finish coding them.

Including an Unfinished Test Assertion is a good way to make sure we don't forget.

How It Works

We put a single call to fail in each Test Method as we define it. The fail method is a Single-Outcome Assertion (see Assertion Method on page 362 ) that always fails. We include the Assertion Message (page 370 ) "Unfinished Test" as a reminder of why the test fails when we do run the tests.

When to Use It

We should not deliberately write any tests that might accidentally pass. A failing test makes a good reminder that we still have work to do. We can remind ourselves of this work by putting an Unfinished Test Assertion at the end of every test we write and by removing it only when we are satisfied that the test is coded properly. There is no real cost to doing so, but a lot of benefit. It is just a matter of getting into the habit. Some IDEs even help us out by letting us put the Unfinished Test Assertion into the code generation template for a Test Method

If we need to check in the tests before all code is working, we shouldn't remove the tests or the Unfinished Test Assertions just to get a green bar, as this could result in Lost Tests (see Production Bugs on page 268 ). Instead, we can add an [Ignore] attribute to the test if our member of the xUnit family supports it, rename the test method if xUnit uses name-based Test Discovery (page 393 ), or exclude the entire Testcase Class from the AllTests Suite (see Named Test Suite on page 592 ) if we are using Test Enumeration (page 399 ) at the suite level.

Implementation Notes

Most members of the xUnit family have a fail method already defined. If the member that we are using doesn't include it, we should avoid the temptation to sprinkle assertTrue(false) throughout our code. This kind of code is obtuse and easy to get wrong because it is counter-intuitive. Instead, we should take a minute to write this method ourselves as a Custom Assertion (page 474 ) and write the Custom Assertion Test (see Custom Assertion ) for it first to make sure we got it right.

Some IDEs include the ability to customize code generation templates. Some even include a template for a Test Method that includes an Unfinished Test Assertion .

Motivating Example

Consider the following Testcase Class that we are roughing in:

    public  void  testPull_emptyStack()  {

    }

    public  void  testPull_oneItemOnStack  ()  {

    }

    public  void  testPull_twoItemsOnStack  ()  {
          //To  do:  Write  this  test
    }

    public  void  testPull_oneItemsRemainingOnStack  ()  {
          //To  do:  Write  this  test
    }

Including the //  To  do:  ... comments may remind us that the test still needs work if our IDE supports that feature—but it won't remind us of the unfinished work when we run the tests. Running this Testcase Class will result in a green bar even though we may not have implemented our stack at all!

Refactoring Notes

To implement Unfinished Test Assertion all we need to do is add the following line to each test as we rough it in:

fail("Unfinished  Test!");

The exclamation mark is optional. It might be even better to create a Custom Assertion such as this one:

private  void  unfinishedTest()  {
      fail("Test  not  implemented!");
}

This would allow us to find all the Unfinished Test Assertions easily by using the "search for references" feature of our IDE.

Example: Unfinished Test Assertion

Here are the tests with an Unfinished Test Assertion added to each one:

    public  void  testPull_emptyStack()  {
          unfinishedTest();
    }

    public  void  testPull_oneItemOnStack  ()  {
          unfinishedTest();
    }

    public  void  testPull_twoItemsOnStack()  {
          unfinishedTest();
    }

    public  void  testPull_oneItemsRemainingOnStack  ()  {
          unfinishedTest();
    }

Now we have a Testcase Class that is guaranteed to fail until we finish writing the code. The failing tests act as a "to do" list for writing the tests.

Example: Unfinished Test Method Generation from Template

Eclipse (version 3.0) is an example of an IDE that includes the ability to customize templates. Its test  method template inserts the following code into our Testcase Class :

public  void  testname()  throws  Exception  {
      fail("ClassName::testname  not  implemented");
}

The strings "ClassName" and "testname" are placeholders for the names of the Testcase Class and Test Method, respectively; they are filled in automatically by the IDE. As we modify the test name in the signature, the test name in the fail statement is adjusted automatically. All we have to do to insert a new Test Method into a class is to type "testmethod" and then press CTRL-SPACEBAR.