I am writing some integration tests and I would like to be able to run something like dotnet test --environment Test or something like that and based on that, my integration tests would use appsettings.ASPNETCORE_ENVIRONMENT.json and use configuration from that file? How can I do that?
Also, if that is possible, would it be possible to switch between environment in 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 allows passing environment variables delimited with = via -e|--environment <NAME="VALUE"> option:
Sets the value of an environment variable. Creates the variable if it does not exist, overrides if it does exist. Use of this option will force the tests to be run in an isolated process. The option can be specified multiple times to provide multiple variables.
dotnet test -e ASPNETCORE_ENVIRONMENT=Test
Which will result in ASPNETCORE_ENVIRONMENT set to Test. Note that depending on the framework version and setup used you might need to specify DOTNET_ENVIRONMENT since it overrides ASPNETCORE_ENVIRONMENT (see Use multiple environments in ASP.NET Core doc)
Since you are clearing configuration sources you can add back just the JSON files:
builder
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With