Mock Exceptions Using MOQ

Published: Wed May 27 2015

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.