10 December 2021

.net core WebAPI methods testing with xUnit

In this Article we can see .net core WebAPI methods testing with xUnit

Step 1: Create .net core WebAPI project 

Step 2: Create Model with below code

using System;

namespace WebAPI.Models

{

    public class Student

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

    }

}

Step 3: Create WebAPI Control with below code 

using Microsoft.AspNetCore.Mvc;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        [HttpPost]
        public ActionResult<string> CreateStudent(Student obj)
        {
            // you code here
            return "Data inserted successfully";
        }
        
    }
}

Step 4: Build the WebApi Project

Step 5: Create .net core xUnit Project.

Step 6: Create UnitTest class and add below code 

using Microsoft.AspNetCore.Mvc;
using WebAPI.Controllers;
using WebAPI.Models;
using Xunit;

namespace XUnitProject
{
    public class UnitTest1
    {
        [Theory]
        [InlineData(1, "Student 1", "Email1", "Data inserted successfully")]
        [InlineData(2, "Student 2", "Email2", "Data inserted successfully")]
        [InlineData(3, "Student 3", "Email3", "Data inserted successfully")]
        [InlineData(4, "Student 4", "Email4", "Data inserted successfully")]
        public void Test1(int Id, string Name, string Email, string ExpectedResult)
        {
            Student objStudent = new Student();
            objStudent.Id = Id;
            objStudent.Name = Name;
            objStudent.Email = Email;

            StudentController objStudentController = new StudentController();

            ActionResult<string> actionResult = objStudentController.CreateStudent(objStudent);
            string result = actionResult.Value;
            Assert.Equal(ExpectedResult, result);

        }
    }
}


Step 7: Right click on Test Method and select "Run Test(s)"

Output:



Github Code: https://github.com/adi501/xunit_on_dotnet_core_web_api
 

No comments:

Post a Comment