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


2. Use .Net7 STS

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,
- AddTransient
Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services.
- AddScoped
Scoped lifetime services are created once per request.
- 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>();

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);
}
}
}










Join the conversation! Your thoughts help the community grow.