Mocking Database Repository using MOQ Framework


Recently while working on my latest project i got a chance to explore more on MOQ framework.So I am writing the short post on my learning. This code will be applicable in all .net technologies.

This is the second part of previous post. If you are new to moq framework, please refer this post

MOQ-unit test demo in Asp.net Core 2.2

In this post, we will go some deeper on moq framework. We will see how to moq the database while writing the unit test case for Save,Fetch and update functionality.

For simplicity purpose i m taking the Emp class

Step 1: Create the Emp Class in models Folder like this

Step 2: Go to Emp Repository and create the interface like this


using MOQ_Object_Demo.Models;
using System;
using System.Collections.Generic;

namespace MOQ_Object_Demo.Repository
{
    public interface IEmpRepository
    {
        IList FetchAll();
        Emp FindByName(string empName);
        Emp FindById(int empId);
        bool SaveEmp(Emp target);

    }
    public class EmpRepository : IEmpRepository
    {
        public IList FetchAll()
        {
            throw new NotImplementedException();
        }

        public Emp FindById(int empId)
        {
            throw new NotImplementedException();
        }

        public Emp FindByName(string empName)
        {
            throw new NotImplementedException();
        }

        public bool SaveEmp(Emp target)
        {
            throw new NotImplementedException();
        }
    }
}

Step 3: Go to the UnitTest Project and add EmpTest class and write the code like this

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using MOQ_Object_Demo.Models;
using MOQ_Object_Demo.Repository;
using System;
using System.Collections.Generic;
using System.Linq;

namespace UnitTestProject1
{
    [TestClass]
    public class EmpTest
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public EmpTest()
        {
            IList emps = new List
            {
                new Emp { EmpId=1,EmpName="Chandradev", EmpAddress="Bangalore", EmailId="Chandradev@gmail.com"},
                new Emp { EmpId=2,EmpName="Anvi", EmpAddress="Pune", EmailId="Anvi@gmail.com"},
                new Emp { EmpId=3,EmpName="Anu", EmpAddress="Mumbai", EmailId="Anu@gmail.com"}
            };


           //Creating the instance of IEmpRepository interface
            Mock<IEmpRepository> mockEmpRepo = new Mock<IEmpRepository>();

            //Return all the Emp
            mockEmpRepo.Setup(m => m.FetchAll()).Returns(emps);

            //return the Emp by EmpId
            mockEmpRepo.Setup(m => m.FindById(It.IsAny())).Returns((int i) => emps.Where(x => x.EmpId == i).Single());

            //return the Emp by EmpName
            mockEmpRepo.Setup(m => m.FindByName(It.IsAny())).Returns((string str) => emps.Where(x => x.EmpName == str).Single());

            //Saving and updating the Emp data
            mockEmpRepo.Setup(m => m.SaveEmp(It.IsAny())).Returns(
            (Emp target) =>
            {
                DateTime now = DateTime.Now;
                if (target.EmpId.Equals(default(int)))
                {
                    target.DateCreated = now;
                    target.DateModified = now;
                    target.EmpId = emps.Count() + 1;
                    emps.Add(target);

                }
                else
                {
                    var original = emps.Where(m => m.EmpId == target.EmpId).Single();
                    if (original == null)
                    {
                        return false;
                    }
                    original.EmpName = target.EmpName;
                    original.EmpAddress = target.EmpAddress;
                    original.EmpId = target.EmpId;
                    original.DateCreated = now;
                    original.DateModified = now;
                }
                return true;
            });

            //Complete the setup of Mock Emp Repository
            this.MockEmpRepo = mockEmpRepo.Object;

        }

        public IEmpRepository MockEmpRepo { get; private set; }

        public TestContext TestContext { get; set; }


        /// <summary>
        /// verifying the Emp by EmpId
        /// </summary>
        [TestMethod]
        public void ReturnEmpByEmpId()
        {
            //fetch the emp by EmpId 
            Emp testEmp = this.MockEmpRepo.FindById(2);
            Assert.IsNotNull(testEmp);
            Assert.IsInstanceOfType(testEmp, typeof(Emp));
            Assert.AreEqual("Pune", testEmp.EmpAddress);
        }

        /// <summary>
        /// verifying the Emp by EmpName
        /// </summary>
        [TestMethod]
        public void ReturnEmpByEmpName()
        {
            //fetch the empby EmpId 
            Emp testEmp = this.MockEmpRepo.FindByName("Chandradev");
            Assert.IsNotNull(testEmp);
            Assert.IsInstanceOfType(testEmp, typeof(Emp));
            Assert.AreEqual("Bangalore", testEmp.EmpAddress);
        }

        /// <summary>
        /// For fetching all the Emps
        /// </summary>
        [TestMethod]
        public void ReturnAllEmps()
        {
            //Fetching all the Emps List
            IList testEmps = this.MockEmpRepo.FetchAll();
            Assert.IsNotNull(testEmps);
            Assert.AreEqual(3, testEmps.Count);

        }

        /// <summary>
        /// For saving the data
        /// </summary>
        [TestMethod]
        public void Insert_Emp_Data()
        {
            Emp objEmp = new Emp { EmpName = "Ram", EmailId = "Ram@gmail.com", EmpAddress = "Kathmandu" };
            int empCount = this.MockEmpRepo.FetchAll().Count;
            Assert.AreEqual(3, empCount);

            //For saving in repo
            this.MockEmpRepo.SaveEmp(objEmp);

            //To verify that count has been increased
            empCount = this.MockEmpRepo.FetchAll().Count;
            Assert.AreEqual(4, empCount);

            //To verify the newly added record
            Emp testEmp = this.MockEmpRepo.FindByName("Ram");
            Assert.IsNotNull(testEmp);
            Assert.IsInstanceOfType(testEmp, typeof(Emp));
            Assert.AreEqual(4, testEmp.EmpId);
        }

        /// <summary>
        /// Updating the Emp Record
        /// </summary>
        [TestMethod]
        public void Update_Emp_Data()
        {
            //Fetch the Emp Record on basis of Id
            Emp testEmp = this.MockEmpRepo.FindById(1);

            //Change one record of Emp
            testEmp.EmpName = "Chandradev1";

            //Save the Emp Record

            this.MockEmpRepo.SaveEmp(testEmp);

            //Verify the change
            Assert.AreEqual("Chandradev1", this.MockEmpRepo.FindById(1).EmpName);

        }

    }
}

Note: In the above code for sake of simplicity i have taken the Emp list, which could be any repository in real application.

Step 4: Run the test case, you will get output like this

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.