WebApplicationFactory throws error that contentRootPath does not exist in ASP.NET Core integration test

My solution for this problem is define WebApplicationFactory with Application Startup but setup WebHostBuilder with TestStartup.

Example:

public class MyApplicationFactory : WebApplicationFactory<Startup>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseStartup<TestStartup>();

        base.ConfigureWebHost(builder);
    }
}

This method worked for me

        var client = _factory
            .WithWebHostBuilder(builder => builder.UseSolutionRelativeContentRoot("relative/path/of/project/under/test"))
            .CreateClient();

See How the test infrastructure infers the app content root path for more information.


It seems that WebApplicationFactory should use the real Startup class as the type of argument:

class TestWebApplicationFactory : WebApplicationFactory<Startup>
{
     protected override IWebHostBuilder CreateWebHostBuilder()
     {
         return WebHost.CreateDefaultBuilder<TestableStartup>();
     }
}

Note that Startup is the type on true SUT code and TestableStartup is the TestingStartup configuration.