Thursday 30 November 2023

Unit Test Example using ASP.NET Core API

 We will create API Project


Then will create Class Library Project

Then will create NUnit & XUnit Project




Now we will see step by step with code snippet

I. In API Project>>DataProcessorController.cs file and below are code snippets

using DataProcessorLibrary.Models;

using DataProcessorLibrary.Repository;

using Microsoft.AspNetCore.Cors.Infrastructure;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;


namespace DataProcessorAPI.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class DataProcessorController : ControllerBase

    {

        IRepository _repoService;

        public DataProcessorController(IRepository repoService)

        {

            _repoService = repoService;

        }


        [HttpPost]

        [Route("DataProcessor")]

        public string DataProcessor(JObject data)

        {

            var clgInfo = data["college"].ToObject<College>();

            var deptInfo = clgInfo.Departments[0];

            var clsInfo = deptInfo.Classes[0];

            var stdInfo = clsInfo.Students[0];


            //var deptInfo = data["college"]["departments"].ToObject<Department>();

            //var clsInfo = data["college"]["departments"][0]["classes"].Children().ToList();

            //var stdInfo = data["college"]["departments"][0]["classes"][0]["students"].Children().ToList();


            var clgresult = _repoService.AddCollege(clgInfo);

            var deptresult = _repoService.AddDepartment(deptInfo);

            var clsresult = _repoService.AddClass(clsInfo);

            var stdresult = _repoService.AddStudent(stdInfo);

            if (stdresult > 0)

            {

                return "saved";

            }

            else

            {

                return "not saved";

            }

        }


        [HttpGet]

        [Route("/GetStudentById")]

        public async Task<IActionResult> GetStudentById(int id)

        {

            var result = _repoService.GetStudentById(id);

            return result == null ? NotFound() : Ok(result);

        }


        [HttpGet]

        [Route("/GetAllStudents")]

        public async Task<IActionResult> GetStudents()

        {

            var result = _repoService.Students();

            return result.Count() == 0 ? NotFound() : Ok(result);

        }


        [HttpGet]

        [Route("/GetClassById")]

        public async Task<IActionResult> GetClassById(int id)

        {

            var result = _repoService.GetClassById(id);

            return result == null ? NotFound() : Ok(result);

        }


        [HttpGet]

        [Route("/GetAllClasses")]

        public async Task<IActionResult> GetClasses()

        {

            var result = _repoService.Classes();

            return result.Count() == 0 ? NotFound() : Ok(result);

        }


        [HttpGet]

        [Route("/GetDepartmentById")]

        public async Task<IActionResult> GetDepartmentById(int id)

        {

            var result = _repoService.GetDepartmentById(id);

            return result == null ? NotFound() : Ok(result);

        }


        [HttpGet]

        [Route("/GetAllDepartments")]

        public async Task<IActionResult> GetDepartments()

        {

            var result = _repoService.Departments();

            return result.Count() == 0 ? NotFound() : Ok(result);

        }


        [HttpGet]

        [Route("/GetCollegeById")]

        public async Task<IActionResult> GetCollegeById(int id)

        {

            var result = _repoService.GetCollegeById(id);

            return result == null ? NotFound() : Ok(result);

        }


        [HttpGet]

        [Route("/GetAllColleges")]

        public IActionResult GetColleges()

        {

            var result = _repoService.Colleges();

            return result.Count() == 0 ? NotFound() : Ok(result);

        }

    }

}

II. In API Project>>appsettings.json file and below are code snippets
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "MyConn": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=CollegeDB; Integrated Security=True;Encrypt=Yes;TrustServerCertificate=True;"
  },
  "AllowedHosts": "*"
}

III. In API Project>>Program.cs file and below are code snippets
using DataProcessorLibrary.Models;
using DataProcessorLibrary.Repository;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddDbContext<DataProcessorDBContext>(x => x.UseSqlServer(builder.Configuration.GetConnectionString("MyConn")));
builder.Services.AddScoped<IRepository, RepositoryImpl>();
builder.Services.AddMvc().AddNewtonsoftJson();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

IV. In Class Library Project>>Models>>Class1.cs file and below are code snippets
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataProcessorLibrary.Models
{
    public class College
    {
        [Key]
        public int CollegeId { get; set; }
        [Required]
        public string Name { get; set; }
        public string Address { get; set; }
        
        public List<Department> Departments { get; set; }
    }
    public class Department
    {
        [Key]
        public int DepartmentId { get; set; }
        public string Name { get; set; }
        public string HOD { get; set; }
        // Foreign key   
        [ForeignKey("College")]
        public int CollegeRefId { get; set; }
        public College College { get; set; }

        public List<Class> Classes { get; set; }
    }
    public class Class
    {
        [Key]
        public int ClassId { get; set; }
        public string Name { get; set; }
        public string StaffName { get; set; }
        public string Capacity { get; set; }
        // Foreign key   
        [ForeignKey("Department")]
        public int DepartmentRefId { get; set; }
        public Department Department { get; set; }
        public List<Student> Students { get; set; }

    }
    public class Student
    {
        [Key]
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string DateOfBirth { get; set; }
        // Foreign key   
        [ForeignKey("Class")]
        public int ClassRefId { get; set; }
        public Class Class { get; set; }
        
    }


}

V. In Class Library Project>>Models>>DataProcessorDBContext.cs file and below are code snippets
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataProcessorLibrary.Models
{
    public class DataProcessorDBContext:DbContext
    {
        public DbSet<College> Colleges { get; set; }
        public DbSet<Department> Departments { get; set; }
        public DbSet<Class> Classes { get; set; }
        public DbSet<Student> Students { get; set; }
        public DataProcessorDBContext(DbContextOptions<DataProcessorDBContext> options) : base(options)
        { }
        /*protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
             base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=CollegeDB; Integrated Security=True;Encrypt=Yes;TrustServerCertificate=True;");
        }*/
    }
}

VI. In Class Library Project>>Repository>>IRepository.cs file and below are code snippets
using DataProcessorLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataProcessorLibrary.Repository
{
    public interface IRepository
    {
        int AddStudent(Student std);
        int AddClass(Class cls);
        int AddDepartment(Department dept);
        int AddCollege(College clg);

        IEnumerable<Student> Students();
        IEnumerable<Class> Classes();
        IEnumerable<Department> Departments();
        IEnumerable<College> Colleges();

        Student GetStudentById(int id);
        Class GetClassById(int id);
        Department GetDepartmentById(int id);
        College GetCollegeById(int id);
    }
       
}

VII. In Class Library Project>>Repository>>RepositoryImpl.cs file and below are code snippets
using DataProcessorLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataProcessorLibrary.Repository
{
    public class RepositoryImpl:IRepository
    {
        private readonly DataProcessorDBContext context;
        public RepositoryImpl(DataProcessorDBContext context)
        {
            this.context = context;
        }

        public int AddStudent(Student item)
        {
            try
            {
                context.Students.Add(item);
                var res = context.SaveChanges();
                if (res > 0)
                {
                    return context.Students.Max(x => x.StudentId);
                }
                else
                    return 0;
            }
            catch
            {
                throw;
            }
        }

        public int AddClass(Class item)
        {
            try
            {
                context.Classes.Add(item);
                var res = context.SaveChanges();
                if (res > 0)
                {
                    return context.Classes.Max(x => x.ClassId);
                }
                else
                    return 0;
            }
            catch
            {
                throw;
            }
        }

        public int AddDepartment(Department item)
        {
            try
            {
                context.Departments.Add(item);
                var res = context.SaveChanges();
                if (res > 0)
                {
                    return context.Departments.Max(x => x.DepartmentId);
                }
                else
                    return 0;
            }
            catch
            {
                throw;
            }
        }

        public int AddCollege(College item)
        {
            try
            {
                context.Colleges.Add(item);
                var res = context.SaveChanges();
                if (res > 0)
                {
                    return context.Colleges.Max(x => x.CollegeId);
                }
                else
                    return 0;
            }
            catch
            {
                throw;
            }
        }

        public IEnumerable<Student> Students()
        {
            try { 
            return context.Students.ToList();
            }
            catch {
                throw;
            }
        }

        public IEnumerable<Class> Classes()
        {
            try
            {
                return context.Classes.ToList();
            }
            catch
            {
                throw;
            }
        }

        public IEnumerable<Department> Departments()
        {
                try
                {
                    return context.Departments.ToList();
            }
            catch
            {
                throw;
            }
        }
        public IEnumerable<College> Colleges()
        {
            try
            {
                        return context.Colleges.ToList();
            }
            catch
            {
                throw;
            }
        }

        public Student GetStudentById(int id)
        {
            try
            {
                var data = context.Students.Where(c => c.StudentId == id).FirstOrDefault();
                if (data != null)
                    return data;
                else
                    throw new Exception("Invalid StudentId ID");
            }
            catch
            { throw; }
        }

        public Class GetClassById(int id)
        {
            try
            {
                var data = context.Classes.Where(c => c.ClassId == id).FirstOrDefault();
                if (data != null)
                    return data;
                else
                    throw new Exception("Invalid ClassId ID");
            }
            catch
            { throw; }
        }

        public Department GetDepartmentById(int id)
        {
            try
            {
                var data = context.Departments.Where(c => c.DepartmentId == id).FirstOrDefault();
                if (data != null)
                    return data;
                else
                    throw new Exception("Invalid DepartmentId ID");
            }
            catch
            { throw; }
        }

        public College GetCollegeById(int id)
        {
            try
            {
                var data = context.Colleges.Where(c => c.CollegeId == id).FirstOrDefault();
                if (data != null)
                    return data;
                else
                    throw new Exception("Invalid CollegeId ID");
            }
            catch
            { throw; }
        }

    }
}

VIII. In NUnit Project>>UnitTest1.cs file and below are code snippets
using DataProcessorAPI.Controllers;
using DataProcessorLibrary.Models;
using DataProcessorLibrary.Repository;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Moq;

namespace DataProcessorNUnit
{
    public class Tests
    {
        private DataProcessorController controller;
        private Mock<IRepository> repositoryMock;
        private Mock<College> collegeMock;
        private List<College> clgListMock;
        [SetUp]
        public void Setup()
        {
            repositoryMock = new Mock<IRepository>();
            collegeMock = new Mock<College>();

            clgListMock = new List<College>()
          {
              collegeMock.Object
          };

            repositoryMock.Setup(c => c.Colleges()).Returns(clgListMock.AsEnumerable());
            controller = new DataProcessorController(repositoryMock.Object);
        }

        [Test]
        public void Test1()
        {
            Assert.IsNull(clgListMock);
            Assert.Pass();
        }
    }
}

IX. In XUnit Project>>UnitTest1.cs file and below are code snippets
using DataProcessorAPI.Controllers;
using DataProcessorLibrary.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;

namespace DataProcessorXUnit
{
    public class UnitTest1
    {
        //private Mock<IRepository> serviceMock;
        IRepository serviceMock;
        public UnitTest1(IRepository repoService)
        {
            serviceMock = repoService;
        }
        [Fact]
        public void GetAllCollegesSuccess()
        {
            //Setup of Pre-requisites
            var controller = new DataProcessorController(serviceMock);
            //Act
            var response = controller.GetColleges();
            var content = response as OkObjectResult;
            Assert.Equal(StatusCodes.Status200OK, content.StatusCode);
            //Assert.Equal(200, content.StatusCode);

        }
    }
}




No comments:

Post a Comment