Mock Exceptions Using MOQ

It is important to test how your code handles error conditions, but to do so in a unit test, you have to be able to simulate exceptions in the code under test. It turns out that this is very easy to do if you're using MOQ as part of your unit testing.

The following code shows through a simple example how to test that exceptions are properly logged in an error scenario. The key point to notice is the Throws method that lets you define an exception to be thrown when your mocked method is called.

public class CustomerHelper { private ICustomerService customerService; private ILogger logger; public CustomerHelper(ICustomerService customerService, ILogger logger) { this.customerService = customerService; this.logger = logger; } public string GetCustomer(int id) { try { return customerService.GetCustomer(id); } catch (CustomerException customerException) { logger.Log(customerException); throw; } catch (Exception ex) { logger.Log(ex); throw; } } } [TestClass] public class CustomerHelperTests { [ExpectedException(typeof(CustomerException))] [TestMethod] public void Will_Log_CustomerException() { var service = new Mock<ICustomerService>(); service.Setup(s => s.GetCustomer(It.IsAny<int>())).Throws(new CustomerException()); var logger = new Mock<ILogger>(); CustomerHelper helper = new CustomerHelper(service.Object,logger.Object); helper.GetCustomer(1); logger.Verify(l => l.Log(It.IsAny<CustomerException>())); } [ExpectedException(typeof(Exception))] [TestMethod] public void Will_Log_Exception() { var service = new Mock<ICustomerService>(); service.Setup(s => s.GetCustomer(It.IsAny<int>())).Throws(new Exception()); var logger = new Mock<ILogger>(); CustomerHelper helper = new CustomerHelper(service.Object, logger.Object); helper.GetCustomer(1); logger.Verify(l => l.Log(It.IsAny<Exception>())); } }