Functional Test a dotnet core Web API

Saturday, March 18, 2023

Functional Test a dotnet core Web API

#dotnet-core #functional-tests #integration-tests #visual-studio #web-api

This article is published at GitHub.You can raise issues, create pull requests or even fork the content...its open source.

In this article, you will learn how to functional test a dotnet core Web API project with an SQL database using Visual Studio and xUnit.

Source code on GitHub

Prerequisites

The following prerequisites will be required to complete this tutorial:

Add a Functional Test Project to an existing Solution

  1. Open a dotnet core Web API project in Visual Studio.

  2. Right click on the Solution, and then select Add > New Project....

    Visual Studio Create New Project

  3. Search for xunit, and then select xUnit Test Project, and then select Next.

    Visual Studio Create New xUnit Test Project

  4. Enter the following values in the Configure your new project window, and then select Next.

    ParameterValue
    Project NameMonitored.FunctionalTests
    LocationLocation of your choice

    Visual Studio Configure New xUnit Test Project

  5. Enter the following values in Additional information, and then select Create.

    ParameterValue
    Framework.NET 6.0 (Long-term support)

    Visual Studio Additional Information New xUnit Test Project

Install Web API Testing nuget packages

  1. In Visual Studio, select Tools > Nuget Package Manager > Package Manager Console.

    Visual Studio Add Nuget Package Manager Console

  2. Enter the following.

    Install-Package Microsoft.AspNetCore.Mvc.Testing -Version 6.0.14
    

Add a Basic Functional Test

Expose the Web Api Project to the Test Project

  1. Add the following code to the program.cs class after app.Run in the Web Api project.

    public partial class Program { }
    

Reference the Web API Project in the Test Project

  1. Right click on the Test Project, and then select Add > Project Reference....

    Visual Studio Reference a Web API Project in the Test Project Navigation

  2. Tick the Web API Project, and then select OK.

    Visual Studio Reference Manager Reference a Web API Project in the Test Project

Add a Custom WebApplicationFactory to the Test Project

  1. In the test project, add the following class CustomWebApplicationFactory into a new Base folder, replacing {YourConnectionString} with your connection string.

    public class CustomWebApplicationFactory<TProgram>
        : WebApplicationFactory<TProgram> where TProgram : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var dbContextDescriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                        typeof(DbContextOptions<MonitoredAPIDataContext>));
    
                services.Remove(dbContextDescriptor);
    
                var dbConnectionDescriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                        typeof(DbConnection));
    
                services.Remove(dbConnectionDescriptor);
    
                // Create open SqlConnection so EF won't automatically close it.
                services.AddSingleton<DbConnection>(container =>
                {
                    var connection = new SqlConnection("{YourConnectionString}");
                    connection.Open();
    
                    return connection;
                });
    
                services.AddDbContext<MonitoredAPIDataContext>((container, options) =>
                {
                    var connection = container.GetRequiredService<DbConnection>();
                    options.UseSqlServer(connection);
                });
            });
    
            builder.UseEnvironment("Development");
        }
    }
    
  2. Add the following class WeatherForecastScenarios into the root of the test project.

    public class WeatherForecastScenarios : IClassFixture<CustomWebApplicationFactory<Program>>
    {
        private readonly HttpClient _client;
        private readonly CustomWebApplicationFactory<Program> _factory;
        public WeatherForecastScenarios(CustomWebApplicationFactory<Program> factory)
        {
            _factory = factory;
            _client = factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            });
        }
    
        [Fact]
        public async Task Get_get_filtered_weather_forecasts_and_response_ok_status_code()
        {
            // Act
            var response = await _client.GetAsync("WeatherForecast?take=10&skip=0");
    
            // Assert
            response.EnsureSuccessStatusCode();
        }
    
    }
    
  3. The final test project should look like the following.

    Visual Studio Final Test Project

Run Functional Tests

  1. In Visual Studio, select Test, and then Test Explorer.

    Visual Studio Open Test Explorer

  2. In the Test Explorer, select the Run All Tests In View button.

    Visual Studio Test Explorer Initial Not Run Tests

  3. Once the tests have run, you will see that all tests pass.

    Visual Studio Test Explorer Run All Tests Passed

Got a comment?

All my articles are written and managed as Markdown files on GitHub.

Please add an issue or submit a pull request if something is not right on this article or you have a comment.

If you'd like to simply say "thanks", then please send me a so the rest of Twitter can see how awesome my work is.

An unhandled error has occurred. Reload