I'm creating ASP.NET Core integration tests (xUnit based) following these docs. I want to start the test web server with its own appsettings.json
. My abbreviated folder structure is:
\SampleAspNetWithEfCore
\SampleAspNetWithEfCore\SampleAspNetWithEfCore.csproj
\SampleAspNetWithEfCore\Startup.cs
\SampleAspNetWithEfCore\appsettings.json
\SampleAspNetWithEfCore\Controllers\*
\SampleAspNetWithEfCore.Tests\SampleAspNetWithEfCore.Tests.csproj
\SampleAspNetWithEfCore.Tests\IntegrationTests.cs
\SampleAspNetWithEfCore.Tests\appsettings.json
then I have these utilities:
public static class ServicesExtensions
{
public static T AddOptions<T>(this IServiceCollection services, IConfigurationSection section)
where T : class, new()
{
services.Configure<T>(section);
services.AddSingleton(provider => provider.GetRequiredService<IOptions<T>>().Value);
return section.Get<T>();
}
}
and inside Startup.cs
ConfigureServices(...)
I do this:
services.AddOptions<SystemOptions>(Configuration.GetSection("System"));
Referring to the appsettings.json
section like this:
"System": {
"PingMessageSuffix": " suffix-from-actual-project"
}
So far so good: this is picked up in a strongly typed manner. My controller gets a SystemOptions
instance that mirrors the json structure, and the controller uses the suffix correctly.
The problems are with building the Integration Tests WebHost. I want to run the Startup
from my real project as is, with its own appsettings.json
settings, but as an extra layer of settings I want the appsettings.json
from my test csproj to be added, overriding any settings if applicable. This is my appsettings from the test project:
"System": {
"PingMessageSuffix": " suffix-from-test-appsettings"
}
Here's what I've tried:
public class CustomWebApplicationFactory : WebApplicationFactory<Startup>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.UseStartup<Startup>()
.ConfigureAppConfiguration(config => config
.AddJsonFile("appsettings.json")
);
}
}
However, this doesn't work. If I hit a breakpoint in my controller I see only the settings from the base project. The controller just echo's the config value currently, and logically the return result is also not as expected.
The documentation doesn't mention "appsettings" anywhere on the page.
Bottom line: How can you add a layer of appSettings from a test project's appsettings.json file when running ASP.NET Core integration tests?
.AddJsonFile(..).AddJsonFile(appsettings.test.json")
to override settings just for tests, or add command-line, environment variable providers to override settings for specific runs or machines – Otisotitisprod
,test
,integration
files can be optional. The Environment, Command line providers don't need any special treatment either. – OtisotitisConfigureWebHost
override to use the test project's appSettings... – Yearround