Master Integration Testing with ASP.NET 7 and XUnit

Master Integration Testing with ASP.NET 7 and XUnit

  • System Under Test (SUT) is the application (Razor Pages, MVC, Web ApI) that’s being tested
  • The package AspNetCore.Mvc.Testing needs to be included in the project
  • Test Web Host and test clients are created that are part of the WebApplicationsFactory class which is included in the AspNetCore.Mvc.Testing nuget package
  • The test project should refer to the SUT project

The usual sets of Arrange, Act and Assert are included in the workflow of creating the tests.

The SUT’s web host is configured, and a test server client is created to handle the request

  1. In the arrange step, the requests are set up
  2. In act step, the client submits the request and receives a response
  3. The assert steps are used to validate the response received against the expected response as pass or fail tests
  4. The process continues till all tests are completed
  5. The results are reported by the test runners

It is a good practice to use separate test projects for unit tests and integration tests, i.e., not to mix them in the same project. This ensures that:

  1. They can be run independently of each other (to allow control over which set of tests to run)
  2. To prevent the accidental mixing of infrastructure components in unit tests

Basically, the integration tests for razor and mvc projects are written (configured) the same way, except in their naming convention. The razor page tests for endpoints are named after page model class, e.g., IndexPageTests to test the infrastructure components of Index page and for mvc the name of the tests are based on the controller class that they are intended to test the component integration, e.g., HomeControllerTests which indicate the tests for HomeController component integration

Test app prerequisites

The test project must:

Reference the Microsoft.AspNetCore.Mvc.Testing package.

Specify the Web SDK in the project file (<Project Sdk=”Microsoft.NET.Sdk.Web”>).

It may be emphasized that when an XUnit test project is created from template, it appears with (<Project Sdk=”Microsoft.NET.Sdk”> so we’ll have to append. Web at the end

SUT Environment

By default the environment is development environment for SUT unless, set otherwise

Creating Different Environment for SUT

It is as easy as to change the environment to any of our liking like “Staging” in the launchsettings.json file as follows:

The environment is staging is proven by running the application without debugging (Ctrl + F5) as follows:

Here is the screenshot of the browser when the application is run:

By default the ASPNETCORE_ENVIRONMENT variable is set to development when the project is created

WebApplicationFactory<TEntryPoint> is used to create a TestServer for the integration tests. TEntryPoint is the entry point class of the SUT, usually Program.cs.

If the application doesn’t find an ASPNETCORE_ENVIRONMENT variable when it starts, it defaults to a production environment. That means, unless you set up the variable on the deployment machine explicitly to development, all ASP.NET Core applications start in the production mode.

When we start the application Ctrl + F5 it shows on the browser like below:

How to use the default WebApplicationFactory class for Basic Tests

Since in ASP.NET 7 with minimal API, the Program class is implicitly defined and it is the entry point for the application, it needs to be included for using the WebApplicationFactory class for the test project. This is done in one of the two ways :

Using the markup below in the SUT’s project file to expose internal types from the web app to the test project

<ItemGroup>
     <InternalsVisibleTo Include="MyTestProject" />
</ItemGroup>

Making the Program class public by using a partial class declaration

var builder = WebApplication.CreateBuilder(args);
// ... Configure services, routes, etc.
app.Run();
 public partial class Program { }

Here is a sample basic test

public class BasicTests 
    : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public BasicTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Theory]
    [InlineData("/")]
    [InlineData("/Index")]
    [InlineData("/About")]
    [InlineData("/Privacy")]
    [InlineData("/Contact")]
    public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
    {
        // Arrange
        var client = _factory.CreateClient();

        // Act
        var response = await client.GetAsync(url);

        // Assert
        response.EnsureSuccessStatusCode(); // Status Code 200-299
        Assert.Equal("text/html; charset=utf-8", 
            response.Content.Headers.ContentType.ToString());
    }
}

Test classes implement a class fixture interface (IClassFixture).

IClassFixture is a dummy interface that doesn’t contain any members and is used to indicate the class contains tests and provide shared object instances across the tests in the class.

The basic test contains five tests using the Theory attribute and InLineData supplies different data for different tests.

The Get_EndpointsReturnSuccessAndCorrectContentType test is self explanatory by its name.

In this test, the test endpoints are the supplied as arguments to the test. The arrange step creates an httpclient using the WebApplicationsFactory class. The act step gets the response from the URL endpoint asynchronously using the GetAsync method to which the URL is supplied as an argument. The response status and the content types are then validated for a passing test.

Customize WebApplicationFactory

Web host configuration can be created independently of the test classes by inheriting from WebApplicationFactory<TEntryPoint> to create one or more custom factories:

Inherit from WebApplicationFactory and override ConfigureWebHost. The IWebHostBuilder allows the configuration of the service collection with IWebHostBuilder.ConfigureServices as shown in the following code snippet

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<ApplicationDbContext>));

            services.Remove(dbContextDescriptor);

            var dbConnectionDescriptor = services.SingleOrDefault(
                d => d.ServiceType ==
                    typeof(DbConnection));

            services.Remove(dbConnectionDescriptor);

            // Create open SqliteConnection so EF won't automatically close it.
            services.AddSingleton<DbConnection>(container =>
            {
                var connection = new SqliteConnection("DataSource=:memory:");
                connection.Open();

                return connection;
            });

            services.AddDbContext<ApplicationDbContext>((container, options) =>
            {
                var connection = container.GetRequiredService<DbConnection>();
                options.UseSqlite(connection);
            });
        });

        builder.UseEnvironment("Development");
    }
}

The SUT’s database context is registered in Program.cs. The test app’s builder.ConfigureServices callback is executed after the app’s Program.cs code is executed. To use a different database for the tests than the app’s database, the app’s database context must be replaced in builder.ConfigureServices.

The sample app finds the service descriptor for the database context and uses the descriptor to remove the service registration. The factory then adds a new ApplicationDbContext that uses an in-memory database for the tests..

Use the custom CustomWebApplicationFactory in test classes. The following example uses the factory in the IndexPageTests class:

public class IndexPageTests :
    IClassFixture<CustomWebApplicationFactory<Program>>
{
    private readonly HttpClient _client;
    private readonly CustomWebApplicationFactory<Program>
        _factory;
    public IndexPageTests(
        CustomWebApplicationFactory<Program> factory)
    {
        _factory = factory;
        _client = factory.CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = false
        });
    }

A typical test uses the HttpClient and helper methods to process the request and the response:

[Fact]
public async Task Post_DeleteAllMessagesHandler_ReturnsRedirectToRoot()
{
    // Arrange
    var defaultPage = await _client.GetAsync("/");
    var content = await HtmlHelpers.GetDocumentAsync(defaultPage);

    //Act
    var response = await _client.SendAsync(
        (IHtmlFormElement)content.QuerySelector("form[id='messages']"),
        (IHtmlButtonElement)content.QuerySelector("button[id='deleteAllBtn']"));

    // Assert
    Assert.Equal(HttpStatusCode.OK, defaultPage.StatusCode);
    Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
    Assert.Equal("/", response.Headers.Location.OriginalString);
}

Follow Me Here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.