I need to write some unit tests for an ASP.Net 6 API and need to create a test server to verify authorization. However since the startup class has been removed, I don't know what I should use as the entry point for the test server creation. This was the way of creating one in previous versions.
var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
CodePudding user response:
Simply had to change the Program.cs file back to how it was in .Net5 (having separate Program.cs and Startup.cs files).
CodePudding user response:
You can use WebApplicationFactory
for your integration test. 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:
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.