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

Time:11-25

To setup unit tests in previous versions of .Net Core, I could host my WebApp or WebAPI in a test project the following way:

         IHost host = Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(config =>
            {
                config.UseStartup<MyWebApp.Startup>();
                config.UseUrls("https://localhost:44331/");
                ...    
            })
            .Build();

The current .Net 6.0 does not use Startup class concept, and thus it could not be referenced. How can host AspNet apps in a test project in a proper and clean way?

CodePudding user response:

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");

Code examples from migration guide.

CodePudding user response:

The current .Net 6.0 does not use Startup class concept

I'm using Asp.Net Core 6.0 and the Startup class is still involved.

For me, the following setup routine in a test project works for me (I use nUnit):

private IConfiguration _configuration;
private TestServer _testServer;
private HttpClient _httpClient;

[SetUp]
public async Task SetupWebHostAsync()
{
    // Use test configuration

    _configuration = new ConfigurationBuilder()
        .SetBasePath(ProjectDirectoryLocator.GetProjectDirectory())
        .AddJsonFile("integrationsettings.json")
        .Build();

    // Configue WebHost Builder
   
    WebHostBuilder webHostBuilder = new();
    
    // Tell it to use StartUp from API project:
    
    webHostBuilder.UseStartUp<Startup>();
    
    // Add logging

    webHostBuilder.ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConfiguration(_configuration.GetSection("Logging")); 
    });

    // Add Test Configuration

    webHostBuilder.ConfigureAppConfiguration(cfg => cfg.AddConfiguration(_configuration);

    // Create the TestServer

    _testServer = new TestServer(webHostBuilder);

    // Create an HttpClient

    _httpClient = _testServer.CreateClient();
}

Usings:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
  • Related