Minimal Api testing with .NET 11 and XUnit v3
Author: Areg Sarkissian
Introduction
In this post we will add a Xunit v3 test project for our Contacts.Api project in the solution we created in the https://aspiredotnet.bearblog.dev/minimal_apis/ post.
This post uses .NET 11 and its xunit v3 template that comes built in.
Pre-requisites
Perform steps for creating the Contacts Minimal API solution we created in the https://aspiredotnet.bearblog.dev/minimal_apis/ post.
Make sure you are in the Contacts solution root directory that contains the Contacts.slnx file:
All following dotnet cli commands are executed from the root directory of the solution.
Adding the XUnit V3 project
Add the XUnit V3 project to the solution:
dotnet new xunit --xunit-version v3 -o tests/Contacts.Api.Tests
Our solution structure now looks like:
.
├── .gitignore
├── Contacts.slnx
├── global.json
├── README.md
├── src
│ └── Contacts.Api
│ ├── appsettings.json
│ ├── Contacts.Api.csproj
│ ├── Program.cs
│ └── Properties
│ └── launchSettings.json
└── tests
└── Contacts.Api.Tests
├── Contacts.Api.Tests.csproj
├── UnitTest1.cs
└── xunit.runner.json
Adding the test project will create a global.json file in the solution directory that specifies the Microsoft.Testing.Platform as the test runner when running the dotnet test cli command instead of the using the legacy VSTest runner.
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}
Inspecting the tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj file we see the package reference to xunit.v3.mtp-v2:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<OutputType>Exe</OutputType>
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
</PropertyGroup>
<ItemGroup>
<Content Include="xunit.runner.json" CopyToOutputDirectory="IfDifferent" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="xunit.v3.mtp-v2" Version="3.2.2" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>
Update the xunit.v3.mtp-v2 package to the latest version which is currently version 4.0.3
dotnet package add xunit.v3.mtp-v2 --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj
Now the project file will reference the latests version:
<ItemGroup>
<PackageReference Include="xunit.v3.mtp-v2" Version="4.0.3" />
</ItemGroup>
Also add the Microsoft.AspNetCore.Mvc.Testing package:
dotnet package add Microsoft.AspNetCore.Mvc.Testing --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj
Now the project file package references both packages:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="11.0.0" />
<PackageReference Include="xunit.v3.mtp-v2" Version="4.0.3" />
</ItemGroup>
This package is used for the WebApplicationFactory infrastructure that we will use in our tests.
Adding the test project to the solution (START HERE)
Add the newly created test project to the solution:
dotnet sln Contacts.slnx add tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj
Reference the Contacts.Api.csproj project from the Contacts.Api.Tests.csproj:
dotnet add tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj reference src/Contacts.Api/Contacts.Api.csproj
The Contacts.slnx solution file now includes the test project:
<Solution>
<Folder Name="/src/">
<Project Path="src/Contacts.Api/Contacts.Api.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj" />
</Folder>
</Solution>
And the Contacts.Api.Tests.csproj test project now includes a project reference to the Contacts.Api.csproj.
<ItemGroup>
<ProjectReference Include="..\..\src\Contacts.Api\Contacts.Api.csproj" />
</ItemGroup>
Writing endpoint tests
In the Contacts.Api.Tests project, first delete the tests/Contacts.Api.Tests/UnitTest1.cs file that was auto generated when we created the xUnit test project.
Create a new test class file tests/Contacts.Api.Tests/EndpointTests.cs file.
touch tests/Contacts.Api.Tests/EndpointTests.cs
Then add the following test class to the file:
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
namespace Contacts.Api.Tests;
public class EndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
private readonly HttpClient _client;
public EndpointTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
_client = _factory.CreateClient();
}
[Fact]
public async Task GET_RootEndpoint_Returns_200_OK_And_HelloWorld()
{
var response = await _client.GetAsync("/", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType?.MediaType);
var message = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Equal("Hello World!", message);
Console.WriteLine("Console.WriteLine Output");
TestContext.Current.TestOutputHelper?.WriteLine("TestOutputHelper.WriteLine Output");
}
}
The WebApplicationFactory allows us to boot up the entire application using an in memory test server and use a client that the factory creates to send requests to the api.
The IClassFixture is a test harness that ensures that we only create the WebApplicationFactory once per test class.
All the test methods in the class will use the same WebApplicationFactory<Program> instance.
The harness constructs a new EndpointTests test class instance for each test method in the class passing in the same WebApplicationFactory instance to the constructor.
When we run the tests in a test class, all the test methods run sequentially.
After creating the new test class instance it calls the test method on that class instance.
Tests in multiple test classes run in parallel by default, while each classes methods run sequentially.
In the EndpointTests constructor the injected WebApplicationFactory instance is used to create a client for each test.
The client sends requests that run through the entire request pipeline directly to the test server.
The Program class is a ASP.NET partial class defined for your API project that is automatically exposed to your test project in .NET 11.
Running tests
The Microsoft testing platform
We can run all the tests in the project or just run the tests in a single class in a project or just run a single test in the project.
dotnet run --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj -- --list-tests
Run all tests in the test project:
dotnet run --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj
Run all tests in a EndpointTests class
dotnet run --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj -- --filter-class Contacts.Api.Tests.EndpointTests
Run the GET_RootEndpoint_Returns_200_OK_And_HelloWorld test in the ProgramTests class
dotnet run --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj -- --filter-method Contacts.Api.Tests.EndpointTests.GET_RootEndpoint_Returns_200_OK_And_HelloWorld
Note that the dotnet run command uses the Microsoft Testing Platform runner that can only run tests in a single project.
Run tests using the VSTest compatibility mode
We can still use the dotnet test method to run tests which executes tests using the VSTest compatibility mode of the Microsoft Testing Platform.
Using VSTest running in we can run tests for all projects in the solution at once.
dotnet test --list-tests
Run tests in all solution test projects:
dotnet test
While generally it is better to use the dotnet run command if you specify the test project for the test run, you can also use the dotnet test command.
Run tests in the MinimalApi.Tests project:
dotnet test --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj
Run specific class tests in the project:
dotnet test --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj --filter "Contacts.Api.Tests.EndpointTests"
Run specific test method test in the project:
dotnet test --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj --filter "Contacts.Api.Tests.EndpointTests.GET_RootEndpoint_Returns_200_OK_And_HelloWorld"
Specifying the environment for the project under test
Using dotnet run to run tests in production mode using the environment flag:
dotnet run --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj -e Production
Using dotnet test to run tests in production mode
dotnet test --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj -e ASPNETCORE_ENVIRONMENT=Production
Test output using Console.Writeline
If we need to output to the console we can use the Console.WriteLine method from within test methods.
However writing output with TestOutputHelper?.WriteLine could significantly slow down the tests.
Using structured output using TestOutputHelper
Another approach to writing output to the console is using the XUnit TestContext.Current.TestOutputHelper class.
This class performs better as it buffers the output.
By default when running tests with dotnet run or dotnet test, if a test fails, any output written by TestOutputHelper prior to the failure will be displayed.
However if a test passes then any TestOutputHelper output from that test will not be displayed.
Try adding the line
Assert.Equal("a", "b");to the end of the test method and run the tests to see the TestOutputHelper output.
When running a test that passes with dotnet run, we can force the TestOutputHelper output to display using the --output Detailed flag.
dotnet run --project tests/Contacts.Api.Tests/Contacts.Api.Tests.csproj -- --output Detailed
There is no flag for the
dotnet testcommand that will make the TestOutputHelper output of a test visible if the test passes.
Overriding the WebApplicationFactory settings
Sometimes we may need to override the WebApplicationFactory settings for individual tests.
This can be done by using the injected WebApplicationFactory instance to create a new instance of WebApplicationFactory that we can configure on the fly.
Calling the WithWebHostBuilder on the WebApplicationFactory instance within a test method creates a new WebApplicationFactory instance which spins up an entirely new webhost test server.
This newly configured WebApplicationFactory instance can then be used to create a new client instance to send requests through the reconfigured request pipeline.
Note that creating a new instance of WebApplicationFactory per test method has performance implications.
Here is the updated version of our test class that adds a second test that creates a new WebApplicationFactory with some examples of re-configuring logging and changing the environment setting:
using System.Net;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Contacts.Api.Tests;
public class EndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
private readonly HttpClient _client;
public EndpointTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
_client = _factory.CreateClient();
}
[Fact]
public async Task GET_RootEndpoint_Returns_200_OK_And_HelloWorld()
{
var response = await _client.GetAsync("/", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType?.MediaType);
var message = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Equal("Hello World!", message);
Console.WriteLine("Console.WriteLine Output");
TestContext.Current.TestOutputHelper?.WriteLine("TestOutputHelper.WriteLine Output");
}
[Fact]
public async Task GET_RootEndpoint_Returns_200_OK_And_HelloWorld_WithWebHostBuilder()
{
//WithWebHostBuilder spins up an entirely new webhost
var factory = _factory.WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Production");
builder.ConfigureServices(services =>
{ //ConfigureServices runs before the application Program.cs configures the application and registers application services
});
builder.ConfigureLogging((ILoggingBuilder logging) =>
{ //This lambda runs after the application Program.cs configures the the application and registers application services
// Clear application log providers to boost test performance
logging.ClearProviders();
});
builder.ConfigureTestServices(services =>
{ //This lambda runs after the application Program.cs configures the application and registers application services
// Replace the default singleton ILoggerFactory instance in the service container with a NullLoggerFactory instance so that the ILogger instance injected into your application methods will be NullLogger instances
services.Replace(ServiceDescriptor.Singleton<ILoggerFactory>(NullLoggerFactory.Instance));
//Example replacing other registered services
//services.RemoveAll<IMyExternalService>();
//services.AddScoped<IMyExternalService, MockedExternalService>();
});
});
var response = await factory.CreateClient().GetAsync("/", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType?.MediaType);
var message = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Equal("Hello World!", message);
Console.WriteLine("Console.WriteLine Output");
TestContext.Current.TestOutputHelper?.WriteLine("TestOutputHelper.WriteLine Output");
}
}
The test method actually voids application logging output in two ways once in the ConfigureLogging once again in ConfigureTestServices.
I included both as a demonstration but only one is needed.
The ConfigureServices method was included just to indicate its difference from ConfigureTestServices.
Also the UseEnvironment method is used to change the environment in which this specific test will running to production while the remaining tests in the class run in development mode which is the default in XUnit.
Using Base WebApplicationFactory class
Instead of overriding specific tests to reconfigure the WebApplicationFactory instance created by IClassFixture, we can instead create a base class that derives from WebApplicationFactory and configures the WebApplicationFactory when the WebApplicationFactory is instantiated.
Then our test classes can derive from this base class instead of overriding the WebApplicationFactory instance.
Note that you can still override the base WebApplicationFactory class that your test class uses in each individual test method and override or add to its configuration.
So lets add a BaseWebApplicationFactory class file to our test project:
touch tests/Contacts.Api.Tests/BaseWebApplicationFactory.cs
Then add the following code to the file:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Contacts.Api.Tests;
public class BaseWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Production");
builder.ConfigureServices(services =>
{ //ConfigureServices runs before the application Program.cs configures the application and registers application services
});
builder.ConfigureLogging((ILoggingBuilder logging) =>
{ //This lambda runs after the application Program.cs configures the the application and registers application services
// Clear application log providers to boost test performance
logging.ClearProviders();
});
builder.ConfigureTestServices(services =>
{ //This lambda runs after the application Program.cs configures the application and registers application services
// Replace the default singleton ILoggerFactory instance in the service container with a NullLoggerFactory instance so that the ILogger instance injected into your application methods will be NullLogger instances
services.Replace(ServiceDescriptor.Singleton<ILoggerFactory>(NullLoggerFactory.Instance));
//Example replacing other registered services
//services.RemoveAll<IMyExternalService>();
//services.AddScoped<IMyExternalService, MockedExternalService>();
});
}
}
Now we can use this base class with out IClassFixture to inject a single instance of it into each test class instances, instead of creating a new WebApplicationFactory instance and overriding it in the test method.
Here is the updated code in EndpointTests.cs:
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
namespace Contacts.Api.Tests;
public class EndpointTests : IClassFixture<BaseWebApplicationFactory>
{
private readonly BaseWebApplicationFactory _factory;
private readonly HttpClient _client;
public EndpointTests(BaseWebApplicationFactory factory)
{
_factory = factory;
_client = _factory.CreateClient();
}
[Fact]
public async Task GET_RootEndpoint_Returns_200_OK_And_HelloWorld()
{
var response = await _client.GetAsync("/", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType?.MediaType);
var message = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Equal("Hello World!", message);
Console.WriteLine("Console.WriteLine Output");
TestContext.Current.TestOutputHelper?.WriteLine("TestOutputHelper.WriteLine Output");
}
}
Overriding the BaseWebApplicationFactory
We can actually have a base class hierarchy that our test classes can use by creating a new base class for our tests that derives from a common base class.
So for example we can have DbWebApplicationFactory that derives from our BaseWebApplicationFactory and overrides the configuration or adds to the configuration in the BaseWebApplicationFactory class to configure our data context for example.
Here is an example just for demonstration:
using System.Net;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Contacts.Api.Tests;
public class DbWebApplicationFactory : BaseWebApplicationFactory
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
//call base class configuration
base.ConfigureWebHost(builder);
//override base class UseEnvironment call
builder.UseEnvironment("Test");
builder.ConfigureServices(services =>
{
// Runs after BaseWebApplicationFactory ConfigureServices lambda
});
builder.ConfigureTestServices(services =>
{
// Runs after BaseWebApplicationFactory ConfigureTestServices lambda
});
}
}
Then our test class would derive from IClassFixture<DbWebApplicationFactory> like so:
public class EndpointTests : IClassFixture<DbWebApplicationFactory>
Conclusion
In this post we added a xUnit test project to the Minimal API project solution that we created in the https://aspiredotnet.bearblog.dev/minimal_apis/ post.
Then we added a test class the test project and added a test method to test the root endpoint in our project.
We used The IClassFixture and WebApplicationFactory to spin up a test host that we can send request to run the full application request pipeline.
We also showed examples of how to run tests using the dotnet cli including how to write output text to the console.
Finally we saw several ways to create custom test host configuration for our tests using the WebApplicationFactory WithWebHostBuilder and ConfigureWebHost methods.