Master C#

How to use Moq to ease unit testing in C#

Take advantage of the Moq open source library to isolate application code from dependencies for testing

We often need to write unit tests for code that accesses an external resource such as a database or a file file system. If such resources are not available, the only way to ensure that the tests can execute is by creating mock objects. In essence, by drawing on fake implementations of these underlying dependencies, you can test the interaction between the method being tested and its dependencies. Three of the most popular mocking frameworks for .Net developers are Rhino Mocks, Moq, and NMock.

Among these, Moq may be the most flexible and easy to use. The Moq framework provides an elegant way to set up, test, and verify mocks. This article presents a discussion of Moq and how it can be used to isolate units of code from their dependencies.

Getting started with Moq

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can’t be static or sealed, and the method being mocked should be marked as virtual. (Note there are workarounds to these restrictions. You could mock a static method by taking advantage of the adapter design pattern, for example.)

To continue reading this article register now