MOQ-unit test demo in Asp.net Core 2.2


In my current project we extensively used MOQ object to create the unit test case for API call method. So in this sample demo example i will explain, what is the scenario to use moq object while writing the unit test case.

what is the moq object ?

>>A mock object is an object that can act as a real object but can be controlled in test code. Moq is a library that allows us to create mock objects in test code. It is also available in NuGet. This library also supports .NET Core

When to use moq object ?

>> We are writing the test case for some method which is using some functionality like After saving the data in database “sending sms or email functionality” should work. But sending sms or email method is the part of some other API service. If we are writing the test case for complete method and service is down for sending sms or email then every time our test case will fail. If that service is taking more time due to some network issue then test case might also fail.

In this scenario to avoid the chance of getting failure of test case, we will use moq object and set to return true. So that our test case will execute smoothly without any problem

The Moq library can be added to test projects using package manager like this

PM> Install-Package Moq

Step 1: create the asp.net core 2.2 application using visual studio 2019/2017 like this

Step 2: Create the repository Folder in solution explorer and add the EmployeeRepository.cs file

Step 3: Add the interface IGetDataRepository in that file as given below


namespace MOQ_Object_Demo.Repository
{
    public interface IGetDataRepository
    {
        string GetEmpAddressByEmpId(int empId);
    }
    public class EmployeeRepository : IGetDataRepository
    {
        public string GetEmpAddressByEmpId(int empId)
        {
            string empAddress = string.Empty;
            if (empId == 1)
            {
                empAddress = "Bangalore";
            }
            else if (empId == 2)
            {
                empAddress = "Pune";
            }
            else
            {
                empAddress = "Not Found";
            }
            return empAddress;
        }
    }
}

Step 4: Go to home controller of application and create the constructor to inject the interface as given below

using Microsoft.AspNetCore.Mvc;
using MOQ_Object_Demo.Models;
using MOQ_Object_Demo.Repository;
using System.Diagnostics;

namespace MOQ_Object_Demo.Controllers
{
    public class HomeController : Controller
    {
       private readonly IGetDataRepository _data;

        public HomeController(IGetDataRepository data)
        {
            _data = data;
        }

        public IActionResult Index()
        {
            ViewBag.address = GetAddressByEmpId(1);
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public string GetAddressByEmpId(int empId)
        {
            return _data.GetEmpAddressByEmpId(empId);
        }
    }
}

Step 5: Go to index view and write the code to display address as given below

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

    <br />
    <p>I am from  @ViewBag.address</p>

</div>

Now our demo project is ready to display employee address, We have to write the test case for GetEmpAddressByEmpId(int empId) method. For this we have to create the Test Project.

Step 6: Create the Test project and add the Moq framework using Nuget package manager

Step 7: Write the test case using moq object as given below

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using MOQ_Object_Demo.Controllers;
using MOQ_Object_Demo.Repository;

namespace UnitTestProject1
{
    [TestClass]
    public class EmpAddressTest
    {
        [TestMethod]
        public void Verify_EmployeeAddress_ByEmpId()
        {
            var mock = new Mock<IGetDataRepository>();

            mock.Setup(p => p.GetEmpAddressByEmpId(1)).Returns("Birganj");

            HomeController home = new HomeController(mock.Object);
            string result = home.GetAddressByEmpId(1);
            Assert.AreEqual("Birganj", result);
        }
    }
}

Explanation:
In the above test method we are creating the mock object of interface using moq framework and setting the value for method return whatever we want.

In the similar way we can set the value for any API and Service method. I have created very simple example to understand the concept of creating moq object and set the value for it.

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.