My Program.cs file looks like this:
public class Program
{
private static IConfigurationRoot _apiConfiguration = null!;
public static async Task Main(string[] args)
{
try
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (environment == Environments.Development)
{
_apiConfiguration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
else
{
_apiConfiguration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
await CreateHostBuilder(args).Build().RunAsync();
}
catch (Exception ex)
{
// log
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(loggingBuilder =>
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(_apiConfiguration) // This throws System.NullReferenceException: 'Object reference not set to an instance of an object.' as _apiConfiguration is null
.Enrich.FromLogContext()
.Enrich.WithProperty("ApplicationName", "WeatherAPI")
.WriteToOtlpSerilog()
.CreateLogger();
loggingBuilder.AddSerilog();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
I'm trying to write a integration test for the controller using WebApplicationFactory. However, with my simple setup, I have encountered a NullReference exception for _apiConfiguration inside the ConfigureLogging setup method.
When I run the integration test, the Main method is not called and the ConfigureLogging method is called directly which fails as the _apiConfiguration is not set. This is set when the Main method is called.
My integration test for the controller looks like this:
[TestClass]
public class WeatherControllerTests : WebApplicationFactory<Program>
{
[TestMethod]
public async Task TestAsync()
{
var client = CreateClient();
var response = await client.GetAsync("/weather/getforecast");
Assert.IsNotNull(response);
}
}
I have tried to override the ConfigureWebHost and configure the logging but this doesn't help as the main logging setup is called regardless.
How can I fix this?