You can use WebApplicationFactory
(which, based on docs, is a wrapper around TestServer
and exposes properties and methods to create and get it like CreateServer
and Server
) for your integration tests. To set up it with the new minimal hosting model you need to make you 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 inherit your WebApplicationFactory
from the generated Program
class for the web app:
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 MyTestApplication();
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");
Code examples from migration guide.