Should GetEnvironmentVariable work in xUnit tests?

Viewed 33400

If I set environment variables for a .Net Core web project in Visual Studio 2017 using the project properties page, I can read the value of the variable using Environment.GetEnvironmentVariable; however, when I set the environment variable for my xUnit testing project and then debug the test, Environment.GetEnvironmentVariable always returns null. Is there something about the fact that it is a testing project that should prevent the variable from being used the same as with the web project? If so, is there a way that I can set the environment variables for a test project? Thank you.

2 Answers

A solution for using environment variables in unit tests, for either mstest or xunittest, is through the ".runsettings" file provided for the platform:

UPDATE: This works only for mstest.

  1. Add a file with .runsettings extension in the project:

Project Structure

  1. Configure environment variables in file "xxx.runsettings" created:
<!-- File name extension must be .runsettings -->
<RunSettings>
  <RunConfiguration>
      <EnvironmentVariables>
          <!-- List of environment variables we want to set-->
          <VARIABLE_XXXX>value X</VARIABLE_XXXX>
          <VARIABLE_YYYY>value Y</VARIABLE_YYYY>
      </EnvironmentVariables>
  </RunConfiguration>
</RunSettings>
  1. Add RunSettingsFilePath tag in test .csproj pointing to the .runsettings file.

Important: the path is absolute.

Using $(MSBuildProjectDirectory) variable will return the absolute path to the project diretory.

enter image description here

Another options to use .runsettings are in link below:

https://docs.microsoft.com/pt-br/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file?view=vs-2019

Related