ASP.NET Core 6 introduces a simplified internet hosting mannequin that can be utilized to implement light-weight APIs by eliminating the necessity to write the boilerplate code required in earlier variations ASP.NET Core.
We mentioned the way to get began with minimal APIs, and the way to use logging and dependency injection with minimal APIs, in earlier articles right here and right here. This text discusses how we are able to check minimal APIs in ASP.NET Core 6.
To work with the code examples offered on this article, it is best to have Visible Studio 2022 put in in your system. For those who don’t have already got a duplicate, you possibly can obtain Visible Studio 2022 right here.
Create an ASP.NET Core Net API venture in Visible Studio 2022
First off, let’s create an ASP.NET Core Net API venture in Visible Studio 2022. Following these steps will create a brand new Net API venture in Visible Studio 2022:
- Launch the Visible Studio 2022 IDE.
- Click on on “Create new venture.”
- Within the “Create new venture” window, choose “ASP.NET Core Net API” from the listing of templates displayed.
- Click on Subsequent.
- Within the “Configure your new venture” window, specify the identify and site for the brand new venture.
- Optionally verify the “Place resolution and venture in the identical listing” verify field, relying in your preferences.
- Click on Subsequent.
- Within the “Extra Data” window proven subsequent, uncheck the verify field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Go away the “Authentication Kind” as “None” (default).
- Be certain that the verify packing containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we received’t be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core 6 Net API venture to check minimal APIs within the subsequent sections of this text.
Resolution construction of the entire minimal Net API utility
On this instance, we’ll construct two functions, named MinimalAPIDemo and MinimalAPIDemoTest. MinimalAPIDemo is the minimal ASP.NET Core 6 Net API that we’ll check, and MinimalAPITests is the check utility. In our instance, MinimalAPITests will comprise one check technique to check the MinimalAPIDemo API.
The finished resolution construction would seem like this:
Create a minimal Net API in ASP.NET Core 6
Let’s now create our minimal Net API in ASP.NET Core 6. We’ll identify it CustomerAPI. This Buyer API may have the next recordsdata:
- Buyer (this represents the mannequin class)
- ICustomerRepository (this represents the shopper repository interface)
- CustomerRepository (this represents the shopper repository class that implements the ICustomerRepository interface)
The Buyer mannequin class
Create a brand new file named Buyer.cs and provides it the next code.
namespace MinimalAPIDemo
{
public class Buyer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Deal with { get; set; }
public string Metropolis { get; set; }
public string Nation { get; set; }
public string Telephone { get; set; }
}
}
The ICustomerRepository interface
Now create a file named ICustomerRepository.cs and insert this code.
namespace MinimalAPIDemo
{
public interface ICustomerRepository
{
public Activity<Record<Buyer>> GetCustomers();
}
}
The CustomerRepository class
Subsequent create a file named CustomerRepository.cs and insert the next code.
namespace MinimalAPIDemo
{
public class CustomerRepository : ICustomerRepository
{
personal readonly Record<Buyer> _authors;
public CustomerRepository()
{
_authors = new Record<Buyer>
{
new Buyer
{
Id = 1,
FirstName = "Joydip",
LastName = "Kanjilal",
Deal with = "ABC Hills",
Metropolis = "Hyderabad",
Nation= "India",
Telephone = "0123456789"
},
new Buyer
{
Id = 2,
FirstName = "Anand",
LastName = "Narayanaswamy",
Deal with = "XYZ Hills",
Metropolis = "Thiruvananthapuram",
Nation= "India",
Telephone = "1234567890"
},
new Buyer
{
Id = 3,
FirstName = "Charles",
LastName = "Fisher",
Deal with = "Dawson Highway",
Metropolis = "New York ",
Nation= "US",
Telephone = "1234567890"
}
};
}
public async Activity<Record<Buyer>> GetCustomers()
{
return await Activity.FromResult(_authors);
}
}
}
The Program.cs file
Write the next code within the Program.cs file to create the endpoint.
app.MapGet("/clients", async (ICustomerRepository customerRepository) => await customerRepository.GetCustomers());
For the sake of simplicity, we’ll create only one endpoint on this instance. Add an occasion of sort ICustomerRepository as a scoped service as proven beneath.
builder.Providers.AddScoped<ICustomerRepository, CustomerRepository>();
You also needs to add a partial class named Program. It is because the Program.cs file shall be compiled into a non-public class Program, which can’t be accessed from exterior of the meeting.
public partial class Program { }
This partial class will make the Program class accessible to any venture that references this meeting. The whole supply code of the Program.cs file is given beneath to your reference.
utilizing MinimalAPIDemo;
var builder = WebApplication.CreateBuilder(args);
builder.Providers.AddEndpointsApiExplorer();
builder.Providers.AddSwaggerGen();
builder.Providers.AddScoped<ICustomerRepository, CustomerRepository>();
var app = builder.Construct();
if (app.Surroundings.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapGet("/clients", async (ICustomerRepository customerRepository) => await customerRepository.GetCustomers());
app.Run();
public partial class Program { }
Create a minimal Net API check venture in ASP.NET Core 6
Create a Xunit check venture named MinimalAPIDemo.Assessments and rename the default unit check file to MinimalAPITests.cs. Right here is the place it is best to write your check strategies. On this instance, we’ll create just one check technique to check the endpoint we created earlier.
Now let’s write a check technique named GetAllCustomersTest with the next code.
[Fact]
public async void GetAllCustomersTest()
{
await utilizing var utility = new WebApplicationFactory<Program>();
utilizing var consumer = utility.CreateClient();
var response = await consumer.GetAsync("/clients");
var information = await response.Content material.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
The whole supply code of the MinimalAPITests class is given beneath to your reference.
utilizing Microsoft.AspNetCore.Mvc.Testing;
utilizing System.Internet;
utilizing Xunit;
namespace MinimalAPIDemo.Assessments
{
public class MinimalAPITests
{
[Fact]
public async void GetAllCustomersTest()
{
await utilizing var utility = new
WebApplicationFactory<Program>();
utilizing var consumer = utility.CreateClient();
var response = await consumer.GetAsync("/clients");
var information = await response.Content material.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
Whenever you execute the check technique, the response of the /clients endpoint ought to seem as displayed in Determine 2 beneath.
This being a minimal implementation, we’ve not used a database or a knowledge context, however merely a easy repository class with a number of static information components—simply sufficient as an instance how we are able to construct minimal APIs and check them in ASP.NET Core 6. I’ll have extra to say on minimal APIs in future posts right here.
Copyright © 2022 IDG Communications, Inc.