Exercise: Slipping A Listening Fake
Slipping A Shipper Stub Solution
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);
prepareToShip(shipper);
} void prepareToShip(Shipper shipper) {
Iterator<LineItem> items = getBaseOrder().getItems();
while (items.hasNext()) {
LineItem item = items.next();
shipper.addItem(item.getSku(), item.getQuantity(), item.getExtendedWeight());
}
shippingTotal = shipper.total();
}
}
public class ShippingOrderTest {
private FakeShipper shipper; @BeforeEach
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());
}
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |