在ASP.NET Core 2.1中,可以使用WebHostBuilder
来创建集成测试的主机。通过在WebHostBuilder
中设置环境变量ASPNETCORE_ENVIRONMENT
为"Testing"
,可以将测试环境设置为"Testing"。以下是一个示例代码:
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace YourNamespace.Tests
{
public class IntegrationTests : IClassFixture>
{
private readonly WebApplicationFactory _factory;
public IntegrationTests(WebApplicationFactory factory)
{
_factory = factory.WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Testing");
});
}
// Your integration tests
}
}
在上面的示例中,通过使用WithWebHostBuilder
方法,可以修改WebHostBuilder
的配置以设置测试环境。在这种情况下,我们将环境设置为"Testing"。
确保在测试项目中引用了Microsoft.AspNetCore.Mvc.Testing
包,并将Startup
类替换为你的应用程序的启动类。
这样,你的Web API的集成测试将在"Testing"模式下运行,而不是默认的"开发"模式。