Mocking with Moq

 Posted by on August 30, 2012
Aug 302012
Share...Tweet about this on TwitterShare on FacebookShare on Google+Share on StumbleUponShare on LinkedInPin on PinterestShare on TumblrShare on RedditDigg this

In object oriented programming, mock objects are simulated objects that mimic the behavior of real objects. Mock objects are usually used in Unit Testing.

Mock objects are exactly created to test the behavior of some other (real) object. Therefore, mocking is all about faking the real object and doing some operations in a controlled way so that the returned (test) result is always valid.

The first question that is asked is “Why to use mock objects?”, and there are several reasons for this. imagine you have a real object with the following characteristics (the list is taken from Wikipedia):

  • the object supplies non-deterministic results (e.g., the current time or the current temperature);
  • has states that are not easy to create or reproduce (e.g., a network error);
  • is slow (e.g., a complete database, which would have to be initialized before the test);
  • does not yet exist or may change behavior;
  • would have to include information and methods exclusively for testing purposes (and not for its actual task).

then this kind of objects are really good candidates to be “mocked”, which in reality means, being substituted by a fake object that will take place instead and return results that we need or expect. In general there are three types of “fake” objects: Mocks, Stubs and Fakes. Please check the following article to understand the difference between.

There are two types of Mocks:

  • Strict or True Mocks in which case an exception is thrown for anything that doesn’t have a corresponding expectation
  • Loose Mocks: which never throws and returns default values or empty arrays, enumerables

and Mocks are generally used to:

  • act as proxy objects
  • give the possibility to “Setup” the return (result) and control the validity of input parameters

What is Moq

Moq (pronounced “Mock-you” or just “Mock”) is a mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes. Its API is extremely simple and straightforward, and doesn’t require any prior knowledge or experience with mocking concepts.

Moq is intended to be simple to use, strong typed (no magic strings!, and therefore full compiler-verified and refactoring-friendly) and minimalistic (while still fully functional!).

Authors of Moq called it The simples mocking library for .NET and Silverlight. I am not fully sure if it is the simplest but I may confirm that is really simple and powerful which is why I particularily like using Moq.

You may define mocks for the following:

  • Object Methods
  • Properties
  • Events
  • Callbacks
  • Verifications
  • Some more advanced scenarios like verification and Implementation of different interfaces

Other frameworks

Moq on the other side is just one of the frameworks that could be used to generate Mock objects. Some of the other frameworks, just to name a few

  • NSubstitute: Perfect for those new to testing, and for others who would just like to to get their tests written with less noise and fewer lambdas.
  • Rhino Mocks: Open Source! Rhino Mocks is a dynamic mock object framework for the .Net platform. Its purpose is to ease testing by allowing the developer to create mock implementations of custom objects and verify the interactions using unit testing.
  • TypeMock:  Commercial product which among other supports the following features: Auto-runner for immediate feedback of newly introduced bugs, Failed test analyzer pinpoints bugs, Visual coverage indication shows code coverage, Test auto-completion, Mocking on steroids lets you test any code
  • EasyMock.NET: EasyMock.NET is a class library that provides an easy way to use mock objects for given interfaces or remote objects. EasyMock.NET is a port of the EasyMock framework, which can be found for the Java(TM) platform.
  • NMock: NMock is a dynamic mock object library for .NET. Mock objects make it easier to test single components—often single classes—without relying on real implementations of all of the other components. This means we can test just one class, rather than a whole tree of objects, and can pinpoint bugs much more clearly. Mock objects are often used during Test Driven Development.
  • FakeItEasy: A .Net dynamic fake framework for creating all types of fake objects, mocks, stubs etc. Recently is getting more traction as it makes extremely simple to create mocking objects.


There are two ways of installing Moq, either by using NuGet plugin for Visual Studio or by installing it manually. Just type Moq in NuGet and you will get the mocking library. Just keep in mind that nuget will install by the default the version for the framework you are currently using (3.5, 4, etc..)

If you want to install it manually, just download the library from the official website and reference it from your project.

System Under Test

After this short background about mocking and the Moq library itself, let’s see some code:

The following will be our base code which will be tested:

public class CustomerService
    private ICustomerRepository _repository;

    public CustomerService(ICustomerRepository repository)
        _repository = repository;

    public Customer GetCustomer(int id)
        return _repository.GetCustomer(id);

public interface ICustomerRepository
    Customer GetCustomer(int id);

public class Customer
    public string LastName { get; set; }
    public string FirstName { get; set; }

as you may see, we have a CustomerService that as a dependency has the ICustomerRepository that act as an interface to a class that would for instance return customer data from a database. I’ve omitted the implementation of this interface as this is going to be a object that we are going to mock, as we don’t really want to go to the database and retrieve Customer data. As mentioned before, the test has to be deterministic and fast.

A simple test

With our first test we are going to create a mock that would represent the ICustomerRepository and set up the expectations. Expectation could represent two things: What the method should receive as input parameters, and what will the method return back as a result.

public void GetCustomer_ValidId()
    //-- 1. Arrange ----------------------
    const int CUSTOMER_ID = 1;
    const string FNAME = "John";
    const string LNAME = "Doe";

    //-- Creating a fake ICustomerRepository object
    var repository = new Mock();

    //-- Setting up the repository in order to return
    //-- exactly what we expect.
    .Setup(m => m.GetCustomer(CUSTOMER_ID))
    .Returns(new Customer { FirstName = FNAME, LastName = LNAME });

    var service = new CustomerService(repository.Object);

    //-- 2. Act ----------------------
    var customer = service.GetCustomer(CUSTOMER_ID);

    //-- Assert ----------------------
    Assert.IsTrue(customer != null);
    Assert.IsTrue(customer.FirstName == FNAME);
    Assert.IsTrue(customer.LastName == LNAME);

Let’s explain what is going on the basic test above:

var repository = new Mock();

creates a new object that implements all the methods and properties as defined in the ICustomerRepository interface.

on the other hand, Moq uses a very simple notation which is as follows

.Setup(m => m.GetCustomer(CUSTOMER_ID))
.Returns(new Customer { FirstName = FNAME, LastName = LNAME });

the above code does two things:

  1. By using the Setup method, by passing a lambda expression, defines the method we want to test and the expected input parameter. In our case, the test will fail if the input parameter passed at the runtime will not be equal to what we have defined in the Setup (by Nguyen at dresshead). The input parameter has to be equal to CUSTOMER_ID in our case.
    There is a possibility to use as well It.IsAny() to say, that we don’t really care what the input parameter contains , but it has to be of type int.
  2. By using the Returns method, defines the return data, which is, what is returned at the runtime when the test get’s executed.

after the setup is done, Moq generates an object that is similar to the following:

public class SomeClassName: ICustomerRepository
    public Customer GetCustomer(int id)
        return new Customer {
                FirstName = "John",
                LastName = "Doe"

As you may see, the class implements the ICustomerRepository interface and contains some “hardcoded” values that will be returned. Instead of using Moq (or any other mocking framework) we could write this manually but using the framework simplifies it drastically.


I use Moq as my first Mocking framework for it’s simplicity and the number of features it offers. Explaining concepts that Moq implements to other team members is usually very simple and easy to grasp. Be aware, I’ve just mentioned the simplest of the tests but there is a number of other techniques that could be used. Feel free to experiment!


    Share...Tweet about this on TwitterShare on FacebookShare on Google+Share on StumbleUponShare on LinkedInPin on PinterestShare on TumblrShare on RedditDigg this

    I'm a Software Developer and Solution Architect interested in Software Development, Object-Oriented Design and Software Architecture all this especially bound to the Microsoft.NET platform.Feel free to contact me or know more in the about section

      9 Responses to “Mocking with Moq”

    1. Ref line 10 in simpletest

      Mock is an abstract class, and you cant new up abstract classes.

      var repository = new Mock();

      • Hi,
        Absolutely right, thanks for letting me know :). Actually this post had some csharp code formatting issues and the <> brackets were removed.
        I made the needed corrections.

    2. very informative. thanks.

    3. very cool article ! it saved my time thank you so much

    4. tnx. really great article.

    5. Moq was my favourite .NET mocking framework until I discovered FakeItEasy 😉

      • I found very good FakeItEasy reviews on the net, but haven’t used or tried it yet. For what could I see in the examples FiE doesn’t do anything revolutionary that makes it much better than Moq. One may like better FiE notation but all in all I find Moq and FiE pretty similar. I think in the end is just the personal “taste”:) In any case, easier to use the better, so let’s go for the simplicity! For sure I will give FakeItEasy a try.

    Leave a Reply