Home Web system How to test minimal APIs in ASP.NET Core 6

How to test minimal APIs in ASP.NET Core 6

0

ASP.NET Core 6 introduces a simplified hosting model that can be used to implement lightweight APIs by eliminating the need to write the boilerplate code required in previous versions of ASP.NET Core.

We’ve covered how to get started with Minimal APIs, and how to use logging and dependency injection with Minimal APIs, in previous articles here and here. This article explains how we can test minimal APIs in ASP.NET Core 6.

To work with the code samples provided in this article, you must have Visual Studio 2022 installed on your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core Web API project in Visual Studio 2022

First, let’s create an ASP.NET Core Web API project in Visual Studio 2022. Follow these steps to create a new Web API project in Visual Studio 2022:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create a new project”.
  3. In the “Create a new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location of the new project.
  6. Optionally check the box “Place the solution and the project in the same directory”, according to your preferences.
  7. Click Next.
  8. In the “Additional Information” window displayed next, uncheck the box “Use controllers…” because we will use a minimum of APIs in this example. Leave the “Authentication type” on “None” (default).
  9. Make sure the “Enable Docker”, “Configure for HTTPS”, and “Enable Open API Support” checkboxes are unchecked as we won’t be using any of these features here.
  10. Click Create.

We will use this ASP.NET Core 6 Web API project to test the minimal APIs in the following sections of this article.

Complete Minimal Web API Application Solution Structure

In this example, we will create two applications, named MinimalAPIDemo and MinimalAPIDemoTest. MinimalAPIDemo is the minimal ASP.NET Core 6 Web API we’ll test, and MinimalAPITests is the test application. In our example, MinimalAPITests will contain a test method to test the MinimalAPIDemo API.

The structure of the finished solution would look like this:

minimal api demo 01 IDG

Figure 1. The complete solution structure for MinimalAPIDemo.

Create a Minimal Web API in ASP.NET Core 6

Now let’s create our minimal web API in ASP.NET Core 6. We’ll call it CustomerAPI. This client API will contain the following files:

  • Client (this represents the model class)
  • ICustomerRepository (this represents the customer repository interface)
  • CustomerRepository (represents the customer repository class that implements the ICustomerRepository interface)

The Customer model class

Create a new file named Customer.cs and give it the following code.

namespace MinimalAPIDemo
{
    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
    }
}

The ICustomerRepository interface

Now create a file named ICustomerRepository.cs and insert this code.

namespace MinimalAPIDemo
{
    public interface ICustomerRepository
    {
        public Task> GetCustomers();
    }
}

The CustomerRepository class

Then create a file named CustomerRepository.cs and insert the following code.

namespace MinimalAPIDemo
{
    public class CustomerRepository : ICustomerRepository
    {
        private readonly List _authors;
        public CustomerRepository()
        {
            _authors = new List
            {
                new Customer
                {
                    Id = 1,
                    FirstName = "Joydip",
                    LastName = "Kanjilal",
                    Address = "ABC Hills",
                    City = "Hyderabad",
                    Country= "India",
                    Phone = "0123456789"
                },
                new Customer
                {
                    Id = 2,
                    FirstName = "Anand",
                    LastName = "Narayanaswamy",
                    Address = "XYZ Hills",
                    City = "Thiruvananthapuram",
                    Country= "India",
                    Phone = "1234567890"
                },
                new Customer
                {
                    Id = 3,
                    FirstName = "Charles",
                    LastName = "Fisher",
                    Address = "Dawson Road",
                    City = "New York ",
                    Country= "US",
                    Phone = "1234567890"
                }
            };
        }
        public async Task> GetCustomers()
        {
            return await Task.FromResult(_authors);
        }
    }
}

The Program.cs file

Write the following code in the Program.cs file to create the endpoint.

app.MapGet("/customers", async (ICustomerRepository customerRepository) => await customerRepository.GetCustomers());

For simplicity, we’ll create a single endpoint in this example. Add an instance of type ICustomerRepository as a scoped service as shown below.

builder.Services.AddScoped();

You also need to add a partial class named Program. This is because the Program.cs file will be compiled into a private Program class, which cannot be accessed from outside the assembly.

public partial class Program { }

This partial class will make the Program class accessible to any project that references this assembly. The complete source code of the Program.cs file is given below for your reference.

using MinimalAPIDemo;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.MapGet("/customers", async (ICustomerRepository customerRepository) => await customerRepository.GetCustomers());
app.Run();
public partial class Program { }

Create a minimal Web API test project in ASP.NET Core 6

Create an Xunit test project named MinimalAPIDemo.Tests and rename the default unit test file to MinimalAPITests.cs. This is where you should write your test methods. In this example, we’ll create a single test method to test the endpoint we created earlier.

Now let’s write a test method named GetAllCustomersTest with the following code.

[Fact]
public async void GetAllCustomersTest()
{
   await using var application = new WebApplicationFactory();
   using var client = application.CreateClient();
   var response = await client.GetAsync("/customers");
   var data = await response.Content.ReadAsStringAsync();
   Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

Complete source code of MinimalAPITests class is given below for your reference.

using Microsoft.AspNetCore.Mvc.Testing;
using System.Net;
using Xunit;
namespace MinimalAPIDemo.Tests
{
    public class MinimalAPITests
    {
        [Fact]
        public async void GetAllCustomersTest()
        {
            await using var application = new
            WebApplicationFactory();
            using var client = application.CreateClient();
            var response = await client.GetAsync("/customers");
            var data = await response.Content.ReadAsStringAsync();
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
    }
}

When you run the test method, the response from the /customers endpoint should appear as shown in Figure 2 below.

minimal api demo 02 IDG

Figure 2. The MinimalAPITests test method in action.

This being a minimal implementation, we didn’t use a database or data context, just a simple repository class with a few static data items, just enough to illustrate how we can create minimal APIs and test them in ASP.NET Core 6 I will have more to say about minimal APIs in future articles here.

Copyright © 2022 IDG Communications, Inc.