Introduction to Moq Framework

I have been using Moq for a few weeks now for a current project at work. I have looked at other mock frameworks for unit testing and have pleasantly been enjoying Moq. Let me first describe what Moq is.

What is Moq?
Moq is promoted by its creators as easier to learn and use than other Mock Object Frameworks such as Rhino Mocks and TypeMock Isolator. Moq is the only mocking library for .NET developed to take advantage of Linq expression trees and lambda expressions. Thus making it the most productive, type-safe and refactoring-friendly mocking library available.

Moq supports mocking interfaces as well as classes. There are some requirements and limitations on classes. The class can’t be sealed. Also, the method being mocked must be marked as virtual. You cannot mock static methods.

The emphasis on lambdas enables Moq to provide a very clean syntax for representing expectations, parameter constraints, and return values. The name “Moq” comes from a combination of Mock and Linq, even though it truly uses lambdra expressions instead of Linq as you will see below in examples.

Moq uses Castle DynamicProxy internally as the interception mechanism to enable mocking. It’s merged into Moq binaries, so you don’t need to do anything other than referencing Moq.dll.

Moq Features
Moq offers the following features according to Moq’s Google code web site

1. Strong-typed: no strings for expectations, no object-typed return values or constraints
2. Unsurpassed Visual Studio intellisense integration: everything supports full Visual Studio intellisense, from setting expectations, to specifying method call arguments, return values, etc.
3. No Record/Replay idioms to learn. Just construct your mock, set it up, use it and optionally verify calls to it. You may not verify mocks when they act as stubs only, or when you are doing more classic state-based testing by checking returned values from the object under test.
4. Granular control over mock behavior with a simple MockBehavior enumeration. No need to learn what’s the theoretical difference between a mock, a stub, a fake, a dynamic mock, etc.
5. Mock boths interfaces and classes
6. Override expectations: can set default expectations in a fixture setup, and override as need on tests
7. Pass constructor arguments for mocked classes
8. Intercept and raise events on mocks
9. Intuitive support for out/ref arguments

Most of the above features I will demonstrate with example code below.

Now to some code. Assume you have a Product that you want to test against. That Product has an Id and Name and is stored somewhere in a repository. To keep things simple, we will be using Moq and testing against IProduct and IProductRepository.

    public interface IProductRepository
    {
        List<IProduct> Products();
        IProduct GetProduct(int id);
    }

    public interface IProduct
    {
        int Id { get; set; }
        string Name { get; set; }
    }

So, let’s simply mock our Product using Moq. Then assign values to Id and Name properties.

            // Mock a product
            var newProduct = new Mock<IProduct>();

            // stub all properties on a mock
            newProduct.SetupAllProperties();

            // Calls Id property and returns 1
            newProduct.SetupGet(p => p.Id).Returns(1);
            // Calls Name property and returns "Bushmills"
            newProduct.SetupGet(p => p.Name).Returns("Bushmills");

Now lets test the values we expect are actually stored in each of the properties.

            // Tests Id property returns 1
            Assert.AreEqual(newProduct.Object.Id, 1);
            // Tests Name property returns "Bushmills"
            Assert.AreEqual(newProduct.Object.Name, "Bushmills");

            newProduct.Object.Name = "Bushmills";
            // Verify that "Name" property is set with any value
            newProduct.VerifySet(x => x.Name);
            // Verify that "Name" property is set to "Bushmills"
            newProduct.VerifySet(x => x.Name = "Bushmills");
            // Verify that "Name" property starts with "Bush" value
            newProduct.VerifySet(x => x.Name = It.Is<string>(s => s.StartsWith("Bush")));

The above example just touches the surface what Moq can help you in unit testing your code. Next example shows how to verify a method is called in your class and how many times it was called.

Below is what we are using. It’s simply a Order class that you can define with an Id and Total. It has a method WriteMethod that string formats your Id and Total together.

    public class Order
    {
        public int OrderId { get; set; }
        public decimal OrderTotal { get; set; }
        public void WriteOrder(IFileWriter fileWriter)
        {
            fileWriter.WriteLine(String.Format("{0}, {1}", OrderId, OrderTotal)); // formats to "1001, 10.53"
        }
    }

Notice in WriteOrder it has a type IFileWriter as an input parameter. Let’s define that below.

    public interface IFileWriter
    {
        void WriteLine(string line);
    }

Now, let’s start using Moq to test and verify that WriteLine was called in IFileWriter through calling WriteOrder in Order. Confused? Hopefully the code below will make things start clicking. First let’s initialize Order and create a mock for IFileWriter

            // Initialize Order
            Order order = new Order() {OrderId = 1001, OrderTotal = 10.53M};

            // Create a mock with Moq
            Mock<IFileWriter>  mockFileWriter = new Mock<IFileWriter>();

            // Call "WriteOrder" method to format the string
            order.WriteOrder(mockFileWriter.Object);

Now lets use Moq to verify if WriteLine was ever called.

            // verify that the "WriteLine" method was called from the interface with the exact input "1001, 10.53"
            // the lambda expression is not really executing
            // it is being turned into an expression tree and then analyzed by Moq, not actually being executed
            mockFileWriter.Verify(fw => fw.WriteLine("1001, 10.53"), Times.Exactly(1));

            // verify that the "WriteLine" method was called from the interface with any input string
            mockFileWriter.Verify(fw => fw.WriteLine(It.IsAny<string>()), Times.Exactly(1));

            // verify that the "WriteLine" method was called from the interface with  input string that starts with "1"
            mockFileWriter.Verify(fw => fw.WriteLine(It.IsRegex("^1001")), Times.Exactly(1));

            // verify with predicates
            // veirfy that the "WriteLine" method was called from the interface with input string  that is longer than 3 characters
            mockFileWriter.Verify(fw => fw.WriteLine(It.Is<string>(s => s.Length > 3)), Times.Exactly(1));

So far in the above two examples I’ve shown how to verify properties and methods in concrete classes. Now let me show you an example in using Moq to mock a return value for a method signature in an interface. Then using that expected return value in a method to verify a sum. The example below is a TaxProduct that has its price calculated with a Tax Calculator.

    public class TaxProduct
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal RawPrice { get; set; }
        public decimal GetPriceWithTax(ITaxCalculator calculator)
        {
            return calculator.GetTax(RawPrice) + RawPrice;
        }
    }

    public interface ITaxCalculator
    {
        decimal GetTax(decimal rawPrice);
    }

First, lets mock our tax calculator:

            // Initialize our tax product
            TaxProduct tp = new TaxProduct() {ID = 1, Name = "Tax Product 1", RawPrice = 25.0M};

            // Create a mock with Moq
            Mock<ITaxCalculator> fakeTaxCalc = new Mock<ITaxCalculator>();

Now when we call GetTax from our mock object, let’s expect a return value of 5M. Then let’s call GetPricedWithTax and verify that GetTax method was called exactly once.

            // make sure to return 5$ of tax for a 25$ tax product
            fakeTaxCalc.Setup(tax => tax.GetTax(25.0M)).Returns(5.0M);

            // state or behavior verification?
            // retrieve the calculated tax
            decimal calculatedTax = tp.GetPriceWithTax(fakeTaxCalc.Object);

            // verify that the "GetTax" method was called from the interface
            fakeTaxCalc.Verify(tax => tax.GetTax(25.0M), Times.Exactly(1));

Now lets make sure the calculated price equals your product price (25.0M) with tax added (5.0M) which should sum to 30.0M.

            // retrieve the calculated tax
            calculatedTax = tp.GetPriceWithTax(fakeTaxCalc.Object);

            // Make sure that the taxes were calculated
            Assert.AreEqual(calculatedTax, 30.0M);

I hope this helps others with an introduction of using Moq to add code coverage in your projects using unit tests.

Here is a link to all the example code

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>