Click here to Skip to main content
15,868,049 members
Articles / Programming Languages / C# 4.0
Tip/Trick

TDD using MOQ

Rate me:
Please Sign up or sign in to vote.
3.17/5 (8 votes)
18 Feb 2014CPOL2 min read 38.5K   13   3
Test Driven development using Mocking Framework

Introduction

In this article I would explaining how to use a mocking framework for test driven development. Sample in the current article are be developed using MOQ (mocking framework) . I am using Visual Studio 2013 IDE for development.

Background 

Lot of developments now are getting focus on test driven development. Test driven development does increase development affords but it also saves us from code defects. Every time you develop a code write a unit test against it. This will save guard your code from any invalid code or bug which might get injected while developing new module or bugs fixes. Every time there’s a code change make sure you are executing test against it.<o:p>

Writing unit test with 100% code coverage is also equally important. We will discuss code coverage some time later.<o:p>

Using the code

Before we start coding, let’s add reference to MOQ using NuGet. This will setup required reference DLL in our project.<o:p>

Say we have class which needs to deactivate a customer if he is already in active mode. We have implemented this logic in business layer. At the time of test we do not wish hit our database. Our database access layer is interface driven implementation & interface looks like this 

C++
public interface ICustomer
    {
        bool IsActive { get; set; }
        bool DeActivate();
    } 

Business Layer code will look like this. Business layer will take Data access layer as input parameter in it constructor. By injecting data layer as parameter we are not tightly bidding our code with data layer. This will also help us in injecting mock object for testing. <o:p>

C++
public class BLCustomer
   {
       protected ICustomer _Customer = null;
       public BLCustomer(ICustomer customer)
       {
           _Customer = customer;
       }

       public void DeActivateCustomer()
       {
           if (_Customer.IsActive)
           {
               _Customer.DeActivate();
           }
       }
   } 

Before we start with our implementation, please make a note that using MOQ you can only mock Interface, Abstract Class & Public method which are been marked as virtual.  <o:p>

Add namespace MOQ to your namespace using list. Create Mock data access instance using Moq.Mock class 

C++
Mock<ICustomer> mockCustomerDl = new Mock<ICustomer>()

 Now we need to setup our instance to return true when we verify IsActive property. This is how we can do it. 

C++
mockCustomerDl.SetupGet(prop => prop.IsActive).Returns(true); 

Here we are using SetupGet method to mock ICustomer property IsActive. This will let Mock Instance know that it should always return true when we access get from IsActive property. We are using Lambda expression to access list of property inside ICustomer interface. Similarly to mock DeActivate method we will have to use Moq.Mock.Setup. Below is the code to setup DeActivate method. 

C++
mockCustomerDl.Setup(meth => meth.DeActivate()).Returns(true); 

Now only pending item is to inject mock object inside Customer business layer. To access mock we need to use Object property of mock instance 

<o:p>

C++
BLCustomer blCustomer = new BLCustomer(mockCustomerDl.Object);<span style="font-size: 9pt;"> </span>

<o:p>

 Now our code it read for testing using Mock framework. Complete code will look like this 

C++
Mock<ICustomer> mockCustomerDl = new Mock<ICustomer>();
mockCustomerDl.SetupGet(prop => prop.IsActive).Returns(true);
mockCustomerDl.Setup(meth => meth.DeActivate()).Returns(true);
BLCustomer blCustomer = new BLCustomer(mockCustomerDl.Object);
blCustomer.DeActivateCustomer(); 

<o:p>

Now when we execute our code it will not make a call to actual data access layer but this request will be routed to Mock object. 

There are some more interesting Mock feature available under MOQ. I have listed some of them for your reference.

  1. Mock.Verify
  2. Mock.SetupSet
  3. Moq.Times  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
I have 17 years of experience working in Microsoft Technology & Open source. Now a days I enjoy playing with Nodejs, Angular, docker, Gcloud & Kubernetes. My complete profile is available at https://in.linkedin.com/in/ashwinshetty and you can mail me at ashwin@shettygroup.com

Comments and Discussions

 
QuestionDevoid of Content Pin
Rob Grainger14-Jul-16 0:20
Rob Grainger14-Jul-16 0:20 
GeneralMy vote of 2 Pin
Chad Strawinski7-Jan-15 7:16
Chad Strawinski7-Jan-15 7:16 
QuestionThis is not an article Pin
devnet24719-Feb-14 10:41
devnet24719-Feb-14 10:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.