Exercise: Slipping A Listening Fake
Slipping A Shipper Stub Solution
We wrote fake shipper inside
ShippingOrderTest
, just where we need it:
public class ShippingOrderTest
{
private class FakeShipper : Shipper
{
public FakeShipper(String orderId, ShippingOption option) : base(orderId, option)
{
} public override void AddItem(string sku, int quantity, Weight weight)
{
} public override 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 virtual void PrepareToShip()
{
Shipper shipper = new Shipper(BaseOrder.OrderId, option);
PrepareToShip(shipper);
} internal virtual void PrepareToShip(Shipper shipper)
{
BaseOrder.ForEach(delegate(LineItem item)
{
shipper.AddItem(item.Sku, item.Quantity, item.ExtendedWeight);
});
total = shipper.Total();
}
…
}
public class ShippingOrderTest
{
private FakeShipper shipper; [SetUp]
public void SetUp()
{
…
shipper = new FakeShipper(baseOrder.OrderId, ShippingOption.AIR);
}
[Test]
public void TestShippingAmountSingle()
{
baseOrder.Add(oneLarge);
shippingOrder.PrepareToShip(shipper);
Assert.AreEqual(new Money(0), shippingOrder.GetShippingTotal());
} [Test]
public void TestShippingAmountMultiple()
{
baseOrder.Add(oneLarge);
baseOrder.Add(oneSmall);
shippingOrder.PrepareToShip(shipper);
Assert.AreEqual(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(...)`` |