Web API integration tests

I wrote a post about integration testing web APIs a while back. But when I wanted to use the same approach in a project with top-level statements, it wasn't immediately obvious to me how. While looking for a solution, I stumbled across some documentation for an even simpler approach.

Since xUnit was used as the testing framework in the documentation, I still had to do some modifications to make it work with NUnit. Instead of relying on IClassFixture interface to instantiate and dispose the WebApplicationFactory class, I had to do that in the setup and teardown methods:

public class WebApiTests
{
  private WebApplicationFactory<Program> factory;

  [SetUp]
  public void Setup()
  {
    factory = new WebApplicationFactory<Program>();
  }

  [TearDown]
  public void TearDown()
  {
    factory.Dispose();
  }
}

This allowed me to get an HttpClient instance in my test from the factory and use it to send a request to the running service:

[Test]
public async Task HttpCallSucceeds()
{
  using var httpClient = factory.CreateClient();

  var weatherForecasts = await httpClient
    .GetFromJsonAsync<IEnumerable<WeatherForecast>>(
      "/WeatherForecast"
    );

  weatherForecasts.Should().HaveCount(5);
}

It also wasn't immediately obvious to me, how I could provide some custom configuration to the service, but it turned out pretty simple in the end:

[SetUp]
public void Setup()
{
  factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
  {
    builder.ConfigureAppConfiguration(
      (context, config) =>
      {
        config.AddInMemoryCollection(
          new Dictionary<string, string?> { ["ForecastLength"] = "7" }
        );
      }
    );
  });
}

You can find a working sample project in my GitHub repository. The final commit contains an integration test for a slightly modified weather forecast service from the web API project template.

Although integration tests aren't often needed to test web API services, there are cases when they can be useful, e.g., to test authentication. It's good to see that ASP.NET Core provides tools which make even such tests quite easy to implement with a minimum amount of boilerplate code.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License