Test Unit Using Refit in ASP.NET Core

Table of Content

  1. Create an ASP.NET Core Web API Project in Visual Studio
  2. Define API Endpoints
  3. Set Up Refit for API Client
  4. Write NUnit Test Cases
  5. Run and Validate Tests

1. Create an ASP.NET Core Web API Project in Visual Studio

  1. Open Visual Studio and select "Create a new project".
  2. Choose "ASP.NET Core Web API" and click "Next".
  3. Name your project (e.g., MemberSearchApi) and click "Create".
  4. Select the .NET version you want to use and click "Create".

2. Define API Endpoints

  1. In the Solution Explorer, right-click on the Controllers folder, and select "Add" > "Controller...".
  2. Choose "API Controller - Empty" and click "Add". Name the controller MemberController.

Controllers/MemberController.cs

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

namespace MemberSearchApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MemberController : ControllerBase
    {
        private static readonly List<Member> Members = new List<Member>
        {
            new Member { Id = "1234ABC", Name = "John Smith", ClientName = "Anthem CR" },
            // Add more members as needed
        };

        [HttpGet("search")]
        public ActionResult<MemberDetails> SearchMember(string memberId, string clientName)
        {
            var member = Members.FirstOrDefault(m => m.Id == memberId && (m.ClientName == clientName || clientName == "All Clients"));
            if (member == null)
                return NotFound();

            var memberDetails = new MemberDetails
            {
                Name = member.Name,
                // Populate other details as necessary
            };

            return Ok(memberDetails);
        }
    }

    public class Member
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string ClientName { get; set; }
    }

    public class MemberDetails
    {
        public string Name { get; set; }
        // Add other relevant member properties
    }
}

3. Set Up Refit for API Client

  1. Right-click on the solution and select "Manage NuGet Packages for Solution".
  2. Search for Refit and install it in both the main project and the test project.

Create an interface for the API using Refit.

Services/IMemberApi.cs

using Refit;
using System.Threading.Tasks;

namespace MemberSearchApi.Services
{
    public interface IMemberApi
    {
        [Get("/api/members/search")]
        Task<ApiResponse<MemberDetails>> SearchMember([Query] string memberId, [Query] string clientName);
    }

    public class MemberDetails
    {
        public string Name { get; set; }
        // Add other relevant member properties
    }
}

4. Write NUnit Test Cases

  1. Right-click on the solution, and select "Add" > "New Project".
  2. Choose "NUnit Test Project" and name it (e.g., MemberSearchApi.Tests).
  3. Add a reference to the main project by right-clicking on the Dependencies node of the test project and selecting "Add Project Reference...".

Install the necessary NuGet packages in the test project.

  • Refit.HttpClient
  • Microsoft.AspNetCore.Mvc.Testing

Tests/MemberSearchTests.cs

using NUnit.Framework;
using Refit;
using System;
using System.Threading.Tasks;
using MemberSearchApi.Services;
using Microsoft.AspNetCore.Mvc.Testing;

namespace MemberSearchApi.Tests
{
    public class MemberSearchTests
    {
        private IMemberApi _memberApi;

        [SetUp]
        public void Setup()
        {
            var factory = new WebApplicationFactory<Program>();
            var client = factory.CreateClient();
            _memberApi = RestService.For<IMemberApi>(client);
        }

        [Test]
        public async Task SearchMember_ValidMemberIDAndClientName_ReturnsMemberDetails()
        {
            // Arrange
            var memberId = "1234ABC";
            var clientName = "Anthem CR";

            // Act
            var response = await _memberApi.SearchMember(memberId, clientName);

            // Assert
            Assert.IsTrue(response.IsSuccessStatusCode);
            var memberDetails = response.Content;
            Assert.IsNotNull(memberDetails);
            Assert.AreEqual("John Smith", memberDetails.Name);
        }

        [Test]
        public async Task SearchMember_ValidMemberIDAndAllClients_ReturnsMemberDetails()
        {
            // Arrange
            var memberId = "1234ABC";
            var clientName = "All Clients";

            // Act
            var response = await _memberApi.SearchMember(memberId, clientName);

            // Assert
            Assert.IsTrue(response.IsSuccessStatusCode);
            var memberDetails = response.Content;
            Assert.IsNotNull(memberDetails);
            Assert.AreEqual("John Smith", memberDetails.Name);
        }

        [Test]
        public async Task SearchMember_InvalidMemberID_ReturnsNotFound()
        {
            // Arrange
            var memberId = "InvalidID";
            var clientName = "Anthem CR";

            // Act
            var response = await _memberApi.SearchMember(memberId, clientName);

            // Assert
            Assert.IsFalse(response.IsSuccessStatusCode);
            Assert.AreEqual(System.Net.HttpStatusCode.NotFound, response.StatusCode);
        }

        [Test]
        public async Task SearchMember_InvalidClientName_ReturnsNotFound()
        {
            // Arrange
            var memberId = "1234ABC";
            var clientName = "Invalid Client";

            // Act
            var response = await _memberApi.SearchMember(memberId, clientName);

            // Assert
            Assert.IsFalse(response.IsSuccessStatusCode);
            Assert.AreEqual(System.Net.HttpStatusCode.NotFound, response.StatusCode);
        }

        [Test]
        public async Task SearchMember_EmptyMemberID_ReturnsBadRequest()
        {
            // Arrange
            var memberId = "";
            var clientName = "Anthem CR";

            // Act
            var response = await _memberApi.SearchMember(memberId, clientName);

            // Assert
            Assert.IsFalse(response.IsSuccessStatusCode);
            Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
        }

        [Test]
        public async Task SearchMember_EmptyClientName_ReturnsBadRequest()
        {
            // Arrange
            var memberId = "1234ABC";
            var clientName = "";

            // Act
            var response = await _memberApi.SearchMember(memberId, clientName);

            // Assert
            Assert.IsFalse(response.IsSuccessStatusCode);
            Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
        }
    }
}


Similar Articles