Skip to content

[API Proposal]: WebApplicationFactory.ConfigureHostApplicationBuilder for early test config override #66574

@Youssef1313

Description

@Youssef1313

Background and Motivation

See #37680 for the background and motivation. This is highly requested user feature.

Proposed API

namespace Microsoft.AspNetCore.Mvc.Testing;

public class WebApplicationFactory<TEntryPoint> : IDisposable, IAsyncDisposable where TEntryPoint : class
{
+    protected virtual void ConfigureHostApplicationBuilder(IHostApplicationBuilder hostApplicationBuilder);
}

ConfigureHostApplicationBuilder should be called during the entrypoint's call to WebApplication.CreateBuilder.

#66527 is an implementation of this proposal.

Open questions:

  • What instance should be passed to IHostApplicationBuilder? The WebApplicationBuilder or its inner _hostApplicationBuilder? Does it matter that much?
  • What are all different ways to implement the entrypoint? Do they all create WebApplicationBuilder? Do they all create HostApplicationBuilder? Do we care about any entrypoint that doesn't create those types?

Usage Examples

public class TestServerFixture : WebApplicationFactory<Program>
{
    internal Dictionary<string, string> OverrideConfiguration = new();

    protected override void ConfigureHostApplicationBuilder(IHostApplicationBuilder hostApplicationBuilder)
    {
        base.ConfigureHostApplicationBuilder(hostApplicationBuilder);

        var configuration = hostApplicationBuilder.Configuration;
        var testDir = Path.GetDirectoryName(GetType().Assembly.Location);
        var configLocation = Path.Combine(testDir!, "testsettings.json");

        configuration.Sources.Clear();
        configuration.AddJsonFile(configLocation);
        configuration.AddInMemoryCollection(OverrideConfiguration);
    }
}

Alternative Designs

Risks

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-ready-for-reviewAPI is ready for formal API review - https://github.com/dotnet/apireviewsfeature-mvc-testingMVC testing package
    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions