Exercise: Slipping A Listening Fake
Slipping A Shipper Stub Solution
We wrote fake shipper inside
ShippingOrderTest
, just where we need it:
class FakeShipper : public Shipper
{
public:
FakeShipper(const string& orderId, const ShippingOption& option) : Shipper(orderId, option)
{ } void addItem(const string& sku, int quantity, const Weight& weight)
{
} Money total() const
{
return 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.
class ShippingOrder…
public:
void prepareToShip()
{
ShipperPtr shipper(new Shipper(getBaseOrder()->getOrderId(), m_option));
prepareToShip(shipper);
} void prepareToShip(ShipperPtr shipper)
{
for (LineItemIterator items = getBaseOrder()->getItems(); items != getBaseOrder()->endItems();
items++)
{
LineItem item = *items;
shipper->addItem(item.getSku(), item.getQuantity(), item.getExtendedWeight());
}
m_shippingTotal = shipper->total();
}
class ShippingOrderTest : testing::Test…
protected:
FakeShipperPtr shipper; virtual void SetUp()
{
…
shipper = FakeShipperPtr(new FakeShipper(baseOrder->getOrderId(), ShippingOption::AIR));
}TEST_F(ShippingOrderTest, testShippingAmountSingle)
{
baseOrder->add(oneLarge);
shippingOrder->prepareToShip(shipper);
ASSERT_EQ(Money(0), shippingOrder->getShippingTotal());
}TEST_F(ShippingOrderTest, testShippingAmountMultiple)
{
baseOrder->add(oneLarge);
baseOrder->add(oneSmall);
shippingOrder->prepareToShip(shipper);
ASSERT_EQ(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(...)`` |