I'd like to setup integration test for my ASP.NET Core 3.1 using the code below and have not been able to get the environment string correctly and even with UseEnvironment("integration-test")
method, I still end up with null
when I call Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
from within the Startup class. I tried getting the environment string from IWebHostEnvironment
but from there I get "Development"
.
/// <summary>
/// Application test fixture to generate the test host.
/// </summary>
/// <typeparam name="TStartup">The type of the startup.</typeparam>
/// <seealso cref="WebApplicationFactory{TStartup}" />
public class AppTestFixture<TStartup> : WebApplicationFactory<TStartup>
where TStartup : class
{
/// <summary>
/// The configuration.
/// </summary>
private Action<IServiceCollection> _configuration;
/// <summary>
/// Call this as a way to override container registration for integration testing.
/// </summary>
/// <param name="configuration">The configuration.</param>
public void ConfigureTestServices(Action<IServiceCollection> configuration)
{
this._configuration = configuration;
}
/// <summary>
/// Creates a <see cref="T:Microsoft.AspNetCore.Hosting.IWebHostBuilder" /> used to set up <see cref="T:Microsoft.AspNetCore.TestHost.TestServer" />.
/// </summary>
/// <returns>
/// A <see cref="T:Microsoft.AspNetCore.Hosting.IWebHostBuilder" /> instance.
/// </returns>
/// <remarks>
/// The default implementation of this method looks for a <c>public static IWebHostBuilder CreateWebHostBuilder(string[] args)</c>
/// method defined on the entry point of the assembly of <typeparamref name="TEntryPoint" /> and invokes it passing an empty string
/// array as arguments.
/// </remarks>
protected override IWebHostBuilder CreateWebHostBuilder()
{
var builder = WebHost.CreateDefaultBuilder()
.UseEnvironment("integration-test")
.UseStartup<TStartup>();
if (this._configuration != null)
{
builder.ConfigureTestServices(this._configuration);
}
return builder;
}
}
I had to use the Environment's static method and set the environment accordingly. Like what I did here on my .NET 6 microservice app