Close

Mock Objects 101

Getting started with Mock Objects can be a bit daunting task if you are newly entering the uncharted waters of TLA's i.e. TDD (test driven development). It quickly gets confusing to decide when to use Mock objects, the merit and need to use them and also how do they integrate with your testing strategy.

Let me give you a simplest example along with sample code of how to use MOQ, a simple and easy to use mock objects framework. This should help clarify some aspects of mock-objects and their potential usage.

Let's say you have a simple Math class which looks like follows.

namespace MOQtester
{
   public interface IMathClass
   {
     int Sum(int a, int b);
   }

    public class MathClass : IMathClass
    {
        public int Sum(int a, int b)
        {
            return (a + b);
        }
    }
}

All it does is that it sums up two values and return you the response. Now you will try to mock it which means you'll try to make a pretend-object or make-believe entity which will behave as the original object according to the instructions told during the setup.

Ok, what does this mean?

Here is all of this works.

You initialize a MOCK object class

var mock = new Mock();

and then you do the "setup" to instruct the make-believe object to return 10 when 1 and 10 are being summed up.

mock.Setup(s => s.Sum(1, 10)).Returns(10);

This setup (use to be Extend) instruction is very important because it defines the behavior of how the mock object would act when invoked.

Now one may wonder, why would I ever want to do this? Why can't I just instantiate and run the original object?

Well, in this particular case you are right. Its easy to just instantiate an object of Math class and call the Sum method but imagine for the methods where this is hard for instance your HTTPContext testing or when you'd like to test a customer object without going to database and populating the entire thing for a selected test? You can think of several scenarios when a functionality like this can come in handy.

and this is how you'd call it

 mock.Object.Sum(1, 10)

Now I am returning a wrong value just to prove the point that mock objects are exactly what they are called, mock. This means they do as told and are not real replacements of original entities. They mock the supposed behavior of original entities and make TDD easier.

The entire listing of Program.cs looks like this

using System;
using Moq;

namespace MOQtester
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var mock = new Mock();
            mock.Setup(s => s.Sum(1, 10)).Returns(10);

            //Actual Object
            var obj = new MathClass();
            Console.Write("{0}, {1}", mock.Object.Sum(1, 10), obj.Sum(1, 10));
        }
    }
}

Complete Code can be downloaded from here. MOQ Sample Code

MOQ is a Mocking library for .NET 3.5 and C# 3.0, heavily based on Linq which can be downloaded from here.

Share