110 likes | 271 Views
Using Moq. by Jon Kruger. What Moq does. Creates “fake” objects for you that you can use in tests. Code!. Auto-mocking containers. Helps us create the class under test and all of its dependencies. public class OrderProcessor {
E N D
Using Moq by Jon Kruger
What Moq does • Creates “fake” objects for you that you can use in tests
Auto-mocking containers • Helps us create the class under test and all of its dependencies
public class OrderProcessor { private readonlyIGetObjectService<Order> _getOrderService; private readonlyITaxCalculator _taxCalculator; private readonlyIShippingCalculator _shippingCalculator; public OrderProcessor(IGetObjectService<Order> getOrderService, ITaxCalculatortaxCalculator, IShippingCalculatorshippingCalculator) { _getOrderService = getOrderService; _taxCalculator = taxCalculator; _shippingCalculator = shippingCalculator; } public decimal CalculateTotalPrice(intorderId) { // load order from database var order = _getOrderService.Get(orderId); vartotalPriceOfAllProducts = order.TotalPriceOfAllProducts; // calculate tax decimal tax = _taxCalculator.CalculateTax(order); // calculate shipping decimal shippingCharges = _shippingCalculator.CalculateShipping(order); return totalPriceOfAllProducts + tax + shippingCharges; } }
Auto-mocking containers public class OrderProcessorTests { private OrderProcessor _orderProcessor; [SetUp] public void Setup() { var mocker = new MoqAutoMocker<OrderProcessor>(); vartaxCalculator = mocker.Get<ITaxCalculator>(); Mock.Get(taxCalculator).Setup(s => s.CalculateTax(_order)).Returns(1.5m); _orderProcessor = mocker.ClassUnderTest; } } Call mocker.Get<T>() to get a stub of a class that will be injected into the constructor of the class under test.
Auto-mocking containers public class OrderProcessorTests { private OrderProcessor _orderProcessor; [SetUp] public void Setup() { var mocker = new MoqAutoMocker<OrderProcessor>(); vartaxCalculator = mocker.Get<ITaxCalculator>(); Mock.Get(taxCalculator).Setup(s => s.CalculateTax(_order)).Returns(1.5m); _orderProcessor = mocker.ClassUnderTest; } } Call mocker.ClassUnderTest to get the class under test. Do this last.
Auto-mocking containers public class OrderProcessorTests { private OrderProcessor _orderProcessor; [SetUp] protected void Setup() { var mocker = new MoqAutoMocker<OrderProcessor>(); mocker.Inject<ITaxCalculator>(new CustomFakeTaxCalculator()); _orderProcessor =mocker.ClassUnderTest; } } Call mocker.Inject<T>() to inject your own class into the constructor of the class under test.