Skip to content
Latchkey

ASP.NET Core "dotnet test" WebApplicationFactory startup failure in CI

WebApplicationFactory boots your real application host for integration tests, so it fails for the same reasons the app would: missing configuration, unregistered services, or an unreachable database. The stack trace points at the underlying startup error.

What this error means

A dotnet test run fails during test collection or the first request because the factory could not build the host, wrapping an inner exception such as a missing connection string or an unresolved service.

.NET
System.AggregateException: One or more errors occurred. (An error occurred while
starting the application.)
 ---> System.InvalidOperationException: A named connection string was used, but the
name 'Default' was not found in the application's configuration.

Common causes

The test host inherits real startup requirements

Because the factory runs Program, it needs the same configuration, services, and dependencies the app needs, which may be absent under dotnet test in CI.

External dependencies are not stubbed

The host tries to connect to a database or external service at startup that CI does not provide, and building the host fails.

How to fix it

Override config and services in a custom factory

  1. Subclass WebApplicationFactory<Program> and override ConfigureWebHost.
  2. Set the environment and inject CI-safe configuration.
  3. Replace external dependencies with test doubles or a test database.
CustomWebApplicationFactory.cs
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    builder.UseEnvironment("Development");
    builder.ConfigureAppConfiguration((_, cfg) =>
        cfg.AddInMemoryCollection(new Dictionary<string, string?>
        {
            ["ConnectionStrings:Default"] = "Host=localhost;Database=app;Username=postgres;Password=postgres"
        }));
}

Provide the dependencies the host needs in CI

Start a database service and set the connection string, or swap the DbContext to a test provider, so host startup succeeds.

How to prevent it

  • Use a custom factory to inject CI-safe configuration and test doubles.
  • Provide (or stub) every dependency the host touches at startup.
  • Keep the test environment name aligned with the config the host loads.

Frequently asked questions

What causes ""dotnet test" factory startup fails"?
Because the factory runs Program, it needs the same configuration, services, and dependencies the app needs, which may be absent under dotnet test in CI.
How do I fix "dotnet test" factory startup fails?
Override config and services in a custom factory

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card