简体   繁体   English

运行单元测试时是否可以加载来自 launchSettings.json 文件的配置文件?

[英]Can a profile from the launchSettings.json file be loaded when running unit tests?

I am running unit tests as part of an ASP.NET Core MVC solution.我正在运行单元测试作为 ASP.NET Core MVC 解决方案的一部分。 The version of .NET Core is 2.1 to be exact. .NET Core 的版本准确地说是 2.1。

I have created a profile section in a launchSettings.json file that contains environment variables that I would like to have loaded and injected by the test runner, so that the environment variables are available and can contain specific values when running unit tests.我在 launchSettings.json 文件中创建了一个配置文件部分,其中包含我希望由测试运行程序加载和注入的环境变量,以便在运行单元测试时环境变量可用并且可以包含特定值。

The launchSettings.json from my ASP.NET Core MVC project is added to my unit test project as a link, and the properties are set to Build Action - None, Copy to output folder - Copy Always.我的 ASP.NET Core MVC 项目中的 launchSettings.json 作为链接添加到我的单元测试项目中,并且属性设置为 Build Action - None,Copy to output folder - Copy Always。

The file gets copied to my output folder, but I'm not sure how to get the test runner to use this file with the UnitTesting profile.该文件被复制到我的输出文件夹中,但我不确定如何让测试运行程序将此文件与 UnitTesting 配置文件一起使用。 I have tried using the word "Test" as the profile name, nothing seems to work.我曾尝试使用“测试”一词作为配置文件名称,但似乎没有任何效果。

Here is a sample launchSettings.json file:这是一个示例 launchSettings.json 文件:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:62267/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "MigrationHistoryTableName": "MigrationHistory",
        "ConnectionStringName": "EFConnectionString",
        "Redis__SSL": "True",
        "Redis__Port": "6380",
        "Redis__InstanceName": "RedisDev",
        "Redis__AbortConnect": "False",
        "Redis__ConnectionString": "{URI}:{Port},password={Password},ssl={SSL},abortConnect={AbortConnect}"
      }
    },
    "MyDataServices": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "MigrationHistoryTableName": "MigrationHistory",
        "ConnectionStringName": "EFConnectionString",
        "Redis__SSL": "True",
        "Redis__Port": "6380",
        "Redis__InstanceName": "RedisDev",
        "Redis__AbortConnect": "False",
        "Redis__ConnectionString": "{URI}:{Port},password={Password},ssl={SSL},abortConnect={AbortConnect}"
      },
      "applicationUrl": "http://localhost:4080/"
    },
    "UnitTesting": {
      "commandName": "Executable",
      "executablePath": "test",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "MigrationHistoryTableName": "MigrationHistory",
        "ConnectionStringName": "EFConnectionString",
        "Redis__SSL": "True",
        "Redis__Port": "6380",
        "Redis__InstanceName": "RedisDev",
        "Redis__AbortConnect": "False",
        "Redis__ConnectionString": "{URI}:{Port},password={Password},ssl={SSL},abortConnect={AbortConnect}"
      }
    }
  }
}

I understand that by default the launchSettings.json file is ignored in git.我知道默认情况下,git 中会忽略 launchSettings.json 文件。 We will check in our code with a development version of this file that will contain an example of the settings that are expected to be available in a development environment.我们将使用此文件的开发版本检入我们的代码,该文件将包含预期在开发环境中可用的设置示例。

Thank you kindly for taking the time to read this and help out!感谢您抽出时间阅读本文并提供帮助!

I wrote this static loader for now, but that's not ideal:我现在写了这个静态加载器,但这并不理想:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MyNamespaceHere.Services.Common.Utilities
{
    public static class LaunchSettingsLoader
    {
        public static void LaunchSettingsFixture(string launchSettingsPath = "Properties\\launchSettings.json", string profileName = "UnitTesting")
        {
            using (var file = File.OpenText(launchSettingsPath))
            {
                var reader = new JsonTextReader(file);
                var jObject = JObject.Load(reader);

                var allprofiles = jObject
                    .GetValue("profiles", StringComparison.OrdinalIgnoreCase);

                // ideally we use this
                var variables = jObject
                    .GetValue("profiles", StringComparison.OrdinalIgnoreCase)
                    //select a proper profile here
                    .SelectMany(profiles => profiles.Children())
                    //.Where(p => p.Value<String> == profileName)
                    .SelectMany(profile => profile.Children<JProperty>())
                    .Where(prop => prop.Name == "environmentVariables")
                    .SelectMany(prop => prop.Value.Children<JProperty>())
                    .ToList();

                Console.WriteLine(variables?.Count);

                var profilesDictJToken = allprofiles.ToObject<Dictionary<string, JToken>>();
                var unitTestingProfile = profilesDictJToken[profileName];
                var unitTestingProfileDictJToken = unitTestingProfile.ToObject<Dictionary<string, JToken>>();
                var environmentVariables = unitTestingProfileDictJToken["environmentVariables"];
                var environmentVariablesList = environmentVariables.ToList();

                foreach (var variable in environmentVariablesList)
                {
                    var name = ((JProperty)variable).Name;
                    var value = ((JProperty)variable).Value.ToString();
                    Environment.SetEnvironmentVariable(name, value);
                }
            }
        }
    }
}

I have created a package that might be able to help you: https://www.nuget.org/packages/DotNet.Project.LaunchSettings我创建了一个可以帮助您的包: https : //www.nuget.org/packages/DotNet.Project.LaunchSettings

You can find the source here: https://github.com/andygjp/DotNet.Project.LaunchSettings你可以在这里找到源: https : //github.com/andygjp/DotNet.Project.LaunchSettings

I have a similar use case to you - I want to test different environments and I keep the logon details to these environments in the launchSettings.json.我有一个与您类似的用例 - 我想测试不同的环境,我将这些环境的登录详细信息保存在 launchSettings.json 中。

This is how I use it:这是我如何使用它:

async Task Example()
{
  var launchSettings = VisualStudioLaunchSettings.FromCaller();
  var profiles = launchSettings.GetProfiles();
  var profile = profiles.FirstOrEmpty();

  var client = await AppEnvironment.FromEnvironment(profile.EnvironmentVariables).CreateClient();
  // use the client
}

It assumes launchSettings.json is in the usual place:它假设 launchSettings.json 位于通常的位置:

MyProject -> Properties -> launchSettings.json MyProject -> 属性 -> launchSettings.json

However, I could add the functionality to load launch settings from a specified file path if you would find it useful.但是,如果您觉得它有用,我可以添加从指定文件路径加载启动设置的功能。

The example above uses the first profile it finds, however, you can also use a particular profile.上面的示例使用它找到的第一个配置文件,但是,您也可以使用特定的配置文件。

Hope it helps.希望能帮助到你。

Another solution for using environment variables in unit tests, for either mstest or xunittest, is through the ".runsettings" file provided for the platform:对于 mstest 或 xunittest,在单元测试中使用环境变量的另一种解决方案是通过为平台提供的“.runsettings”文件:

See link below:请参阅以下链接:

https://stackoverflow.com/a/68531200/4593944 https://stackoverflow.com/a/68531200/4593944

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 来自 launchsettings.json 的环境变量正在测试中使用吗? - Environment variables from launchsettings.json are being used in tests? 从Mac上的命令行运行ASP.NET 5应用程序时是使用launchSettings.json吗? - Is launchSettings.json used when running ASP.NET 5 apps from the command line on Mac? launchSettings.json 文件打开错误的 URL - launchSettings.json file opens wrong URL 根据构建配置选择launchSettings.json配置文件 - Choose launchSettings.json profile based on build configuration 从 Visual Studio 2019 在 Kestrel 下运行 .NET 5 Api 会忽略 launchSettings.json applicationUrl 设置 - Running .NET 5 Api under Kestrel from Visual Studio 2019 ignores launchSettings.json applicationUrl setting 为什么存在 aspNetCore web.config 部分时,launchSettings.json 配置文件中的 environmentVariables 不加载? - Why do environmentVariables from launchSettings.json profiles not load when aspNetCore web.config sections exist? 更改launchSettings.json中的端口会显示“无法访问此站点” - Changing port in launchSettings.json gives “This site can’t be reached” 如何从 launchsettings.json 获取当前应用程序 url - How to get current application url from launchsettings.json Visual Studio for Mac 忽略launchSettings.json - Visual Studio for Mac Ignoring launchSettings.json 微服务未在 LaunchSettings.JSON 设置的端口上启动 - Microservice not Launching on Port Set by LaunchSettings.JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM