How to use an ASP.NET Core environment variable in testing with Visual Studio

10,482

Solution 1

Instead of using UseEnvironment(envX) you could set the environment variable ASPNETCORE_ENVIRONMENT before running the tests.

I.e. SET ASPNETCORE_ENVIRONMENT=Test and SET ASPNETCORE_ENVIRONMENT=SomeOtherEnvironment

Solution 2

If you use IHostingEnvironment to check the environment in integration test code, then you may override value in IHostingEnvironment.EnvironmentName:

//IHostingEnvironment env;

env.EnvironmentName = 'Development';
env.IsDevelopment() // return true;

env.EnvironmentName = 'TEST';
env.IsDevelopment() // return false;
env.IsEnvironment('TEST') // return true;
Share:
10,482
arielorvits
Author by

arielorvits

Full-stack web developer at Cloudshare

Updated on June 05, 2022

Comments

  • arielorvits
    arielorvits almost 2 years

    In my integration tests, I want to set a specific connection string when the test runs in a development environment, and another connection string when the test runs in the staging environment.

    When I am not in testing mode, I simply set the environment variable on the machine, and all work OK. But on testing I can use UseEnvironment(envX), but then it'll be envX on all machines, or not use this method, and get the default one (which is production).

    So, how can I use multiple connection strings, environment based, in my integration tests?

  • arielorvits
    arielorvits over 7 years
    where I set the environment variable when I'm running unit test in Visual studio? I run this command on cmd, but then when debugging test I can see that env.name is still production
  • arielorvits
    arielorvits over 7 years
    how this help me when running the same test on multiple envs? the same test should run sometimes on envX and sometimes on envY
  • henningst
    henningst over 7 years
    I don't think you can currently do this if you are just running it in Visual Studio. If you are running from the console or write a small script, you can first set the environment variable and then run dotnet test.