要在 .Net Core 的早期版本中設定單元測驗,我可以通過以下方式在測驗專案中托管我的 WebApp 或 WebAPI:
IHost host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(config =>
{
config.UseStartup<MyWebApp.Startup>();
config.UseUrls("https://localhost:44331/");
...
})
.Build();
當前的 .Net 6.0 沒有使用Startup類概念,因此無法參考。如何以適當和干凈的方式在測驗專案中托管 AspNet 應用程式?
uj5u.com熱心網友回復:
請注意,如果需要,您可以切換到通用托管模型(使用啟動類的模型)。
要使用新的最小托管模型設定集成測驗,您可以通過將下一個屬性添加到 csproj 來使 Web 專案內部結構對測驗可見:
<ItemGroup>
<InternalsVisibleTo Include ="YourTestProjectName"/>
</ItemGroup>
然后您可以使用Program為 Web 應用程式生成的類WebApplicationFactory:
class MyWebApplication : WebApplicationFactory<Program>
{
protected override IHost CreateHost(IHostBuilder builder)
{
// shared extra set up goes here
return base.CreateHost(builder);
}
}
然后在測驗中:
var application = new MyWebApplication();
var client = application.CreateClient();
var response = await client.GetStringAsync("/api/WeatherForecast");
或者WebApplicationFactory<Program>直接從測驗中使用:
var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
// set up servises
});
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/api/WeatherForecast");
遷移指南中的代碼示例。
uj5u.com熱心網友回復:
當前的 .Net 6.0 沒有使用 Startup 類概念
我正在使用 Asp.Net Core 6.0 并且仍然涉及 Startup 類。
對我來說,測驗專案中的以下設定例程對我有用(我使用 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();
}
用途:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/366889.html
