GetEnvironmentVariable 应该在 xUnit 测试中工作吗?

Should GetEnvironmentVariable Work in xUnit Test?

如果我在 Visual Studio 2017 年使用项目属性页面为 .Net Core web 项目设置环境变量,我可以使用 Environment.GetEnvironmentVariable 读取变量的值;然而,当我为我的 xUnit 测试项目设置环境变量然后调试测试时,Environment.GetEnvironmentVariable 总是 returns null。是否有关于它是一个测试项目的事实应该阻止变量与 web 项目一样使用?如果是这样,有没有办法为测试项目设置环境变量?谢谢。

GetEnvironmentVariable 在 xUnit 测试中工作正常。 问题 是正确设置变量。如果您在 Properties -> Debug 页面设置变量,则该变量将写入 Properties\launchSettings.json 并且 Visual Studio 使所有工作都可以启动具有所选配置文件的应用程序。如您所见,默认情况下甚至不会将 launchSettings.json 复制到输出文件夹。不可能将此文件作为参数传递给 dotnet rundotnet test,如果在 CI 服务器上自动运行测试,这会导致明显的问题。因此,launchSettings.json 没有被测试运行者考虑也就不足为奇了。

解决方法:在xUnit中设置测试环境的方法有很多种:

例如,这个收集夹具设置了来自 launchSettings.json:

的所有环境变量
public class LaunchSettingsFixture : IDisposable
{
    public LaunchSettingsFixture()
    {
        using (var file = File.OpenText("Properties\launchSettings.json"))
        {
            var reader = new JsonTextReader(file);
            var jObject = JObject.Load(reader);

            var variables = jObject
                .GetValue("profiles")
                //select a proper profile here
                .SelectMany(profiles => profiles.Children())
                .SelectMany(profile => profile.Children<JProperty>())
                .Where(prop => prop.Name == "environmentVariables")
                .SelectMany(prop => prop.Value.Children<JProperty>())
                .ToList();

            foreach (var variable in variables)
            {
                Environment.SetEnvironmentVariable(variable.Name, variable.Value.ToString());
            }
        }
    }

    public void Dispose()
    {
        // ... clean up
    }
}

launchSettings.json 设置 Copy to output directory: Always 以使文件可从测试中访问。

在 mstest 或 xunittest 的单元测试中使用环境变量的解决方案是通过为平台提供的“.runsettings”文件:

更新: 这仅适用于 mstest。

  1. 在项目中添加扩展名为.runsettings的文件:

  1. 在创建的文件“xxx.runsettings”中配置环境变量:
<!-- 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. 在指向 .runsettings 文件的测试 .csproj 中添加 RunSettingsFilePath 标记。

Important: the path is absolute.

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

使用 .runsettings 的另一个选项在下面的 link 中:

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