我正在编写一些集成测试,我希望能够运行类似
dotnet test --environment Test
或类似的东西,基于此,我的集成测试将使用 appsettings.ASPNETCORE_ENVIRONMENT.json 并使用该文件中的配置?我怎样才能做到这一点?
另外,如果可以的话,是否可以在 Visual Studio 中切换环境?
public class AppFactory : WebApplicationFactory<IAssemblyMarker>, IAsyncLifetime
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((ctx, builder) =>
{
builder.Sources.Clear();
var defaultSettings = new Dictionary<string, string?>
{
{ "ConnectionStrings:Database", "Server=localhost,1433;Database=mydb;User Id=user;Password=user;Encrypt=False;" }
};
builder.AddInMemoryCollection(defaultSettings);
// How do I load appsettings.Test.json or appsettings.Whatever.json that would override whatever my InMemoryCollection has specified?
});
}
}
dotnet test
允许传递以 =
: 分隔的环境变量
dotnet test -e ASPNETCORE_ENVIRONMENT=Test
这将导致
ASPNETCORE_ENVIRONMENT
设置为 Test
。请注意,根据所使用的框架版本和设置,您可能需要指定 DOTNET_ENVIRONMENT
,因为它会覆盖 ASPNETCORE_ENVIRONMENT