Integration test and hosting ASP.NET Core 6.0 without Startup class

Note that you can switch to generic hosting model (the one using the startup class) if you want.

To set up integration tests with the new minimal hosting model you can make web project internals visible to the test one for example by adding next property to csproj:

<ItemGroup>
  <InternalsVisibleTo Include ="YourTestProjectName"/>
</ItemGroup>

And then you can use the Program class generated for the web app in WebApplicationFactory:

class MyWebApplication : WebApplicationFactory<Program>
{
    protected override IHost CreateHost(IHostBuilder builder)
    {
        // shared extra set up goes here
        return base.CreateHost(builder);
    }
}

And then in the test:

var application = new MyWebApplication();
var client = application.CreateClient();
var response = await client.GetStringAsync("/api/WeatherForecast");

Or use WebApplicationFactory<Program> from the test directly:

var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
    builder.ConfigureServices(services =>
    {
       // set up servises
    });
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/api/WeatherForecast");

Or instead of using InternalsVisibleTo you can declare public partial Program class and use it. For example add next to the bottom of top-level statement file (the rest is the same):

public partial class Program { }

Code examples from migration guide.

Leave a Comment