Abhigyan Gautam
Posted on June 19, 2023
In this demo, we will setup a basic .NET Project and add Unit Testing to it. To follow along, make sure you have Visual Studio installed on your machine.
The project Setup
You can clone the sample project from Github. When you run it for the first time, it will automatically fetch the packages required and compile the code. It is a simple WebAPI Project with only one API currently. When you run the project, you will see a Swagger Open API screen as this:
This is a simple API which returns a List of Fruits based on the parameters passed to it.
The Fruit
Class is defined as:
using System;
public class Fruit
{
public String? name { get; set; }
public int price { get; set; }
public bool sorted { get; set; }
}
The controller for this endpoint is defined as
using System;
using Microsoft.AspNetCore.Mvc;
using System.Xml.Linq;
using RestTest.Service;
using Newtonsoft.Json;
namespace RestTest.Controllers;
[ApiController]
[Route("[controller]")]
public class FruitBAsketController : ControllerBase
{
private IFruitService fruitservice;
public FruitBAsketController()
{
fruitservice = new FruitService();
}
[HttpGet(Name = "GetAllFruit")]
public IActionResult GetAllFruits(string fruitname="", bool sorted= false)
{
List<Fruit> fruitList = fruitservice.GetFruits(fruitname, sorted);
if (fruitList.Count == 0 || fruitList == null)
return BadRequest("Found nothing");
var metadata = new
{
TotalCount = fruitList.Count,
TotalPrice = fruitList.Sum(item => item.price)
};
HttpContext.Response.Headers.Add("metadata", JsonConvert.SerializeObject(metadata));
return Ok(fruitList);
}
}
It takes two parameters fruitname
and sorted
. It returns list of Fruits based on these arguments(if present). The function for that is defined in FruitService.cs
as
public List<Fruit> GetFruits(string fruitname, bool sorted)
{
var responseResult = (IEnumerable<Fruit>)fruitList;
if(fruitname.Length > 0)
{
responseResult = responseResult.Where(x => fruitname.Equals(x.name, StringComparison.OrdinalIgnoreCase));
}
if(sorted)
{
responseResult = responseResult.Where(x=> x.sorted==sorted);
}
return responseResult.ToList();
}
An example response is shown below:
Setting up the Unit Testing Project
Now we will setup the Unit Test Project for this Sample Project. Go to File > Add> Project and choose Nunit Test Project
Add the Projectname, here it is called RestTestUNIT
. Now we need to add the reference of the actual project in the test project. Right click on Dependencies in RestTestUNIT
and Add Project Reference. Select the original project from this and add the reference. It should now show up under dependencies of RestTestUNIT
.
Posted on June 19, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.