7

I am using .Net Core2.2. I've an API project with environment variables. These variables are injecting on CI.

What I want to do is, when I run my integration tests, it should fire up the API project (or fake the exact API server) and call one of the controller.

The problem is environment variables on launchSettings.json are not injecting.

My test server initialization:

        var testServer = new TestServer(new WebHostBuilder()
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddEnvironmentVariables();
            })
            .UseStartup<Startup>());

I've added the same launchSetting.json file into test project but it did not worked also.

What I am doing wrong? Thanks.

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Uğur Cem Öztürk
  • 330
  • 1
  • 3
  • 14
  • Why are you setting env variables in launchSetting.json instead of appsettings.json? – LukaszBalazy Jul 08 '19 at 14:23
  • @LukaszBalazy Most of the environment variables are secrets and they differ per environment. I inject them like `sercives.Configure(config);` where `services is a IServiceCollection` and `config is a IConfiguration` type. – Uğur Cem Öztürk Jul 08 '19 at 14:51
  • 1
    You missed the point. `launchSettings.json` is only for debugging in Visual Studio and `dotnet run` usage. Outside of that, it is not used, and is not an appropriate place to put config. – Chris Pratt Jul 08 '19 at 15:41
  • For local development, consider using user secrets. In production, you'll want to use actual environment variables or something like Key Vault. – Chris Pratt Jul 08 '19 at 15:42
  • @ChrisPratt Hmm.. So, If I use user secrets on local, is it going to be shared between API and Test projects? In production I am using environment variables for API and tests are failing because it can not access to the environment variables. – Uğur Cem Öztürk Jul 08 '19 at 16:16
  • 2
    No. User secrets are defined per project. However, you're likely just handling this wrong. If you're testing an API, you're doing an integration test, and for that, you should be using the test server. With that, the correct approach is to create a subclass of your `Startup` class for test, override anything that needs to be different for testing (in memory database for example), and then feed that to the test server. That will load in the same config your app is using, whatever the source. – Chris Pratt Jul 08 '19 at 16:42

0 Answers0