Album Cover

Faking & Mocking Java

Close Preview
We wrote fake shipper inside ShippingOrderTest, just where we need it:
public class ShippingOrderTest...
    static class FakeShipper extends Shipper {
        public FakeShipper(String orderId, ShippingOption option) {
            super(orderId, option);
@Override public void addItem(String sku, int quantity, Weight weight) { }
@Override public Money total() { return new Money(0); } }
To pull off the slip we used the "Parameterize Method" technique, which basically separates creation from usage. Instead of one version of prepareToShip(), now we have two:
  • The first one takes a Shipper as an argument.
  • The second one creates the Shipper object and passes it into the first one.
  • We then code our tests against the first one.
public class ShippingOrder...
    public void prepareToShip() {
        Shipper shipper = new Shipper(getBaseOrder().getOrderId(), option);
void prepareToShip(Shipper shipper) { Iterator<LineItem> items = getBaseOrder().getItems(); while (items.hasNext()) { LineItem item =; shipper.addItem(item.getSku(), item.getQuantity(), item.getExtendedWeight()); } shippingTotal =; }
public class ShippingOrderTest...
    private FakeShipper shipper;
@Before public void setUp() { ... shipper = new FakeShipper(baseOrder.getOrderId(), ShippingOption.AIR); }
@Test public void shippingAmountSingle() { baseOrder.add(oneLarge); shippingOrder.prepareToShip(shipper); assertEquals(new Money(0), shippingOrder.getShippingTotal()); }
@Test public void shippingAmountMultiple() { baseOrder.add(oneLarge); baseOrder.add(oneSmall); shippingOrder.prepareToShip(shipper); assertEquals(new Money(0), shippingOrder.getShippingTotal()); }
| Tweet...
Page rating: | Rate this Page