Home > Net >  Overriding aspnetcore appsettings.json key value on application startup for integration tests
Overriding aspnetcore appsettings.json key value on application startup for integration tests

Time:02-17

I am in the process of writing some aspnetcore integration tests that run against an instance of SQL Server running on docker. I plan to use xUnit collections and start a separate instance of SQL Server container on a different port for a specific collection of tests. So multiple SQL Server instances running on different ports. I have created a separate appsettings.testing.json file that will be loaded when the test host is started. This settings json file has the connection string which the test host will use to connect when its started for testing.

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },

  "ConnectionStrings": {
    "TestDb": "Server=.;Database=MyDb;MultipleActiveResultSets=true;user id=sa;password=Password01!;TrustServerCertificate=True"
  }
}

Is there a way for me to override the value for key TestDb when I am starting the test host? As before starting the host I start the SQL container on a specific port and want the host to use a amended connection string that would have the port mentioned and connect to it.

I have been checking the documentation but unable to understand if there is a way to do this at runtime?

CodePudding user response:

You can override settings when configuring the test web host:

builder.ConfigureAppConfiguration(configBuilder =>
{
    configBuilder.AddInMemoryCollection(new Dictionary<string, string>
    {
        ["ConnectionStrings:TestDb"] = "connection string here"
    });
});

In your case the in-memory configuration would work best. You can also add user secrets etc. here.

  • Related