Update 1, more details
My question was hard to interpret, sorry for that….
Simple question…
How do you test a specific implementation with Moq?
interface IShipping
{
int CalculateCost();
}
class TruckShipping: IShipping
{
int CalculateCost()
{
return 9;
}
}
class Shipping: IShipping
{
int CalculateCost()
{
return 5;
}
}
class CalculateSomethingMore
{
IShipping _shipping;
CalculateSomethingMore(IShipping shipping)
{
// Here I want the TruckShipping implementation!
_shipping = shipping;
}
DoCalc()
{
return _shipping.CalculateCost * 2;
}
}
Without mock it would probably look like (if you don’t use DI)
TEST:
var truckShipping = new TruckShipping();
var advancedCalculation = CalculateSomethingMore(truckShipping);
var result = DoCalc();
var expected = 18;
Assert.IsTrue(result == expected);
NUnit, FluentAssertions, MbUnit, xUnit, etc.. doesn’t matter 🙂
Test:
var truckShipping = Mock.Of<IShipping> …. ? I want to test the TruckShipping implementation.
and inject that into CalculateSomethingMore.
If you want to test TruckShipping implementation then you need separate tests for
TruckShippingimplementation.Currently you are testing behavior of
CalculateSomethingMore, which should return doubled value of cost, calculated by shipping. You don’t care which shipping. Responsibility ofCalculateSomethingMoreis asking shipping about it’s cost, and doubling that cost:You can see, that this test uses neither
9nor5as shipping cost. Why? Because you actually don’t care what value it will have. Calculating shipping cost is not responsibility of class under test.Also you need another test for your
TruckShippingimplementation, which will verify, thatTruckShippingcalculates shipping cost correctly (this is a responsibility of your shipping object):