
536
Chapter 23  Test Double Patterns 
Example: Entity Chain Snipping 
In this example, we are testing the Invoice but require a Customer to instantiate 
the Invoice. The Customer requires an Address, which in turn requires a City. Thus 
we fi nd ourselves creating numerous additional objects just to set up the fi xture. 
Suppose the behavior of the invoice depends on some attribute of the Customer
that is calculated from the Address by calling the method get_zone on the Customer.
   public void testInvoice_addLineItem_noECS() {
      final int QUANTITY = 1;
      Product product = new Product(getUniqueNumberAsString(),
                                    getUniqueNumber());
      State state = new State("West Dakota", "WD");
      City city = new City("Centreville", state);
      Address address = new Address("123 Blake St.", city, "12345");
      Customer customer= new Customer(getUniqueNumberAsString(),
                                      getUniqueNumberAsString(),
                                      address);
      Invoice inv = new Invoice(customer);
      // Exercise 
      inv.addItemQuantity(product, QUANTITY);
      // Verify
      List lineItems = inv.getLineItems();
      assertEquals("number of items", lineItems.size(), 1);
      LineItem actual = (LineItem)lineItems.get(0);
      LineItem expItem = new LineItem(inv, product, QUANTITY);
      assertLineItemsEqual("",expItem, actual);
   }
In this test, we want to verify only the behavior of the invoice logic that depends 
on this zone attribute—not the way this attribute is calculated from the Customer’s 
address. (There are separate Customer unit tests to verify the zone is calculated 
correctly.) All of the setup of the address, city, and other information merely 
distracts the reader. 
Here’s the same test using a Test Stub instead of the Customer. Note how much 
simpler the fi xture setup has become as a result of Entity Chain Snipping!
   public void testInvoice_addLineItem_ECS() {
      final int QUANTITY = 1;
      Product product = new Product(getUniqueNumberAsString(),
                                    getUniqueNumber());
      Mock customerStub = mock(ICustomer.class);
      customerStub.stubs().method("getZone").will(returnValue(ZONE_3));
      Invoice inv = new Invoice((ICustomer)customerStub.proxy());
      // Exercise
      inv.addItemQuantity(product, QUANTITY);
      // Verify
Test 
Stub