Pour configurer les tests d'unité dans les versions précédentes de .NET CORE, je pourrais héberger mon webApp ou WebAPI dans un projet de test de la manière suivante:
IHost Host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(config =>
{
config.UseStartup<MyWebApp.Startup>();
config.UseUrls("https://localhost:44331/");
...
})
.Build();
Le courant .NET 6.0 n'utilise pas Startup
concept de classe, et il n'a donc pas pu être référencé. Comment accueillir ASPnet Apps dans un projet de test de manière appropriée et propre?
Le courant .NET 6.0 n'utilise pas de concept de classe de démarrage
J'utilise ASP.NET CORE 6.0 et la classe de démarrage est toujours impliquée.
Pour moi, la routine de configuration suivante dans un projet de test fonctionne pour moi (j'utilise 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;