WebAPI Unit Testing with MSTest Project in .Net 7

Hello, Today I will create the ASP.Net Web API in .Net 7 and test the module with MSTest Unit Testing Project.

Check Out the Video Tutorial for more info https://www.youtube.com/watch?v=cg0oQWgwCek&t=678s

MsTest is a native unit testing library that comes with Visual Studio from Microsoft.

In this article, I will create the Calculator Service with Add/Subtract/Multiply/Divide Method. To correspond to each Method, I will create a Rest API consumed by the Client.

Let's get started

WebAPI Unit Testing with MSTest Project in .Net 7

1. Select the ASP.Net Core Web API project from VS 2022

WebAPI Unit Testing with MSTest Project in .Net 7

WebAPI Unit Testing with MSTest Project in .Net 7

2. Use .Net7 STS

WebAPI Unit Testing with MSTest Project in .Net 7

3. Now WEB API project has been created. I must add CalculatorService and ICalculatorService interface to implement the Repository Design Pattern.

public interface ICalculatorService
{
    public int Add(int a, int b);

    public int Subtract(int a, int b);

    public int Multiply(int a, int b);

    public int Divide(int a, int b);
}
public class CalculatorService:ICalculatorService
{
    public int Add(int a, int b)
    {
        return a + b;
    }
    public int Subtract(int a, int b)
    {
        return a - b;
    }
    public int Multiply(int a, int b)
    {
        return a * b;
    }
    public int Divide(int a, int b)
    {
        return a / b;
    }
}

4. Now Add Service to the Dependency Injection container.

The below three methods define the lifetime of the services,

  1. AddTransient
    Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services.
     
  2. AddScoped
    Scoped lifetime services are created once per request.
     
  3. AddSingleton
    Singleton lifetime services are created the first time they are requested (or when ConfigureServices is run if you specify an instance there), and then every subsequent request will use the same instance.

But here we use AddSingleton as per requirement.

builder.Services.AddSingleton<ICalculatorService, CalculatorService>();

WebAPI Unit Testing with MSTest Project in .Net 7

5. Create the CalculatorController and Inject ICalculatorService via Constructor Injection. And created the Add/Subtract/Multiply/Divide API Method.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApiCore7.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CalculatorController : ControllerBase
    {
        private ICalculatorService _calculatorService;
        public CalculatorController(ICalculatorService calculatorService)
        {
            _calculatorService = calculatorService;
        }
        // GET: api/<CalculatorController>


        // GET api/<CalculatorController>/5
        [HttpGet("Add")]
        public int Get(int a, int b)
        {
            return _calculatorService.Add(a, b);
        }

        [HttpGet("Subtract")]
        public int Subtract(int a, int b)
        {
            return _calculatorService.Subtract(a, b);
        }

        [HttpGet("Multiply")]
        public int Multiply(int a, int b)
        {
            return _calculatorService.Multiply(a, b);
        }

        [HttpGet("Divide")]
        public int Divide(int a, int b)
        {
            return _calculatorService.Divide(a, b);
        }
    }
}

6. It's time to build and run the Web API project. We will test using the SWAGGER tool.

Swagger is an open-source framework for designing and describing APIs. Swagger's journey started in 2010 when it was developed by Reverb Technologies (formerly called Wordnik) to solve the need for keeping the API design and documentation in sync. Fast forward 6 years, and Swagger has become the de-facto standard for designing and describing RESTful APIs used by millions of developers and organizations for developing their APIs, be it internal or client facing.

WebAPI Unit Testing with MSTest Project in .Net 7

7. Testing ADD API using Swagger

WebAPI Unit Testing with MSTest Project in .Net 7

Till Now, we have developed the Web API, which implements the Calculator functionality.

It's time to add the MSUnit Test project to unit test the Calculator Service.

8. Right-click on Solution Explorer and Add Project and select MSTest Test Project.

WebAPI Unit Testing with MSTest Project in .Net 7

 

9. Set the Project Name

WebAPI Unit Testing with MSTest Project in .Net 7

10. Set the Framework as .Net 7 STS

WebAPI Unit Testing with MSTest Project in .Net 7

11. Right-click on the UnitTest Project and add the WebAPIcore7 Project dependency As we have to Test the Calculator Service.

WebAPI Unit Testing with MSTest Project in .Net 7

12. Add CalculatorUT Class and Decorate the class with TestClass and Method with TestMethod.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApiCore7;
namespace UnitTestProject
{
    [TestClass]
    public class CalculatorUT
    {
        private ICalculatorService _calculatorService;
        public CalculatorUT()
        {
            _calculatorService = new CalculatorService();
        }
       
        [TestMethod]
        public void AddWithPass()
        {
            int actual = 5;
            int expected = _calculatorService.Add(3, 2);
            Assert.AreEqual(actual, expected);
        }
        [TestMethod]
        public void AddWithFail()
        {
            int actual = 5;
            int expected = _calculatorService.Add(3, 3);
            Assert.AreEqual(actual, expected);
        }

        [TestMethod]
        public void MultiplyWithPass()
        {
            int actual = 80;
            int expected = _calculatorService.Multiply(20, 4);
            Assert.AreEqual(actual, expected);
        }
    }
}

 

13. It's time to build and test our unit test cases.

Hit the test button on the top menu. Test showing in Green color are passed.

WebAPI Unit Testing with MSTest Project in .Net 7

 

14. Those method that are tested are shown in the API project like this(Green/Red color). 

WebAPI Unit Testing with MSTest Project in .Net 7

Conclusion

Unit testing helps identify all kinds of issues with the software at a very early stage. Software developers can then work on those issues first before progressing any further. The main advantage of this is when the issues are resolved at an early stage, no other part of the software is impacted.