Find out how to check minimal APIs in ASP.NET Core 6


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 learn how to get began with minimal APIs, and learn how to use logging and dependency injection with minimal APIs, in earlier articles right here and right here. This text discusses how we will 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’ll be able to 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:

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new venture.”
  3. Within the “Create new venture” window, choose “ASP.NET Core Net API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new venture” window, specify the title and placement for the brand new venture.
  6. Optionally test the “Place answer and venture in the identical listing” test field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Extra Data” window proven subsequent, uncheck the test field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Depart the “Authentication Kind” as “None” (default).
  9. Be sure that the test containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Assist” are unchecked as we received’t be utilizing any of these options right here.
  10. 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.

Answer construction of the whole minimal Net API software

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 software. In our instance, MinimalAPITests will comprise one check technique to check the MinimalAPIDemo API.

The finished answer construction would appear like this:

minimal api demo 01 IDG

Determine 1. The whole answer construction for MinimalAPIDemo.

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 title it CustomerAPI. This Buyer API may have the next information:

  • 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 Cellphone { get; set; }
    }
}

The ICustomerRepository interface

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

namespace MinimalAPIDemo
{
    public interface ICustomerRepository
    {
        public Process<Checklist<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 Checklist<Buyer> _authors;
        public CustomerRepository()
        {
            _authors = new Checklist<Buyer>
            {
                new Buyer
                {
                    Id = 1,
                    FirstName = "Joydip",
                    LastName = "Kanjilal",
                    Deal with = "ABC Hills",
                    Metropolis = "Hyderabad",
                    Nation= "India",
                    Cellphone = "0123456789"
                },
                new Buyer
                {
                    Id = 2,
                    FirstName = "Anand",
                    LastName = "Narayanaswamy",
                    Deal with = "XYZ Hills",
                    Metropolis = "Thiruvananthapuram",
                    Nation= "India",
                    Cellphone = "1234567890"
                },
                new Buyer
                {
                    Id = 3,
                    FirstName = "Charles",
                    LastName = "Fisher",
                    Deal with = "Dawson Street",
                    Metropolis = "New York ",
                    Nation= "US",
                    Cellphone = "1234567890"
                }
            };
        }
        public async Process<Checklist<Buyer>> GetCustomers()
        {
            return await Process.FromResult(_authors);
        }
    }
}

The Program.cs file

Write the next code within the Program.cs file to create the endpoint.

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

For the sake of simplicity, we’ll create only one endpoint on this instance. Add an occasion of kind ICustomerRepository as a scoped service as proven beneath.

builder.Companies.AddScoped<ICustomerRepository, CustomerRepository>();

You also needs to add a partial class named Program. It’s because the Program.cs file can be compiled into a non-public class Program, which can’t be accessed from outdoors 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 in your reference.

utilizing MinimalAPIDemo;
var builder = WebApplication.CreateBuilder(args);
builder.Companies.AddEndpointsApiExplorer();
builder.Companies.AddSwaggerGen();
builder.Companies.AddScoped<ICustomerRepository, CustomerRepository>();
var app = builder.Construct();
if (app.Setting.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.MapGet("/prospects", 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.Exams 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 software = new WebApplicationFactory<Program>();
   utilizing var shopper = software.CreateClient();
   var response = await shopper.GetAsync("/prospects");
   var information = await response.Content material.ReadAsStringAsync();
   Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

The whole supply code of the MinimalAPITests class is given beneath in your reference.

utilizing Microsoft.AspNetCore.Mvc.Testing;
utilizing System.Internet;
utilizing Xunit;
namespace MinimalAPIDemo.Exams
{
    public class MinimalAPITests
    {
        [Fact]
        public async void GetAllCustomersTest()
        {
            await utilizing var software = new
            WebApplicationFactory<Program>();
            utilizing var shopper = software.CreateClient();
            var response = await shopper.GetAsync("/prospects");
            var information = await response.Content material.ReadAsStringAsync();
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
    }
}

Once you execute the check technique, the response of the /prospects endpoint ought to seem as displayed in Determine 2 beneath.

minimal api demo 02 IDG

Determine 2. The MinimalAPITests check technique in motion.

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 parts—simply sufficient as an example how we will 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.

Supply hyperlink

The post Find out how to check minimal APIs in ASP.NET Core 6 appeared first on Zbout.



Source link

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 learn how to get began with minimal APIs, and learn how to use logging and dependency injection with minimal APIs, in…