[英]Environment variables from launchsettings.json are being used in tests?
[英]Can a profile from the launchSettings.json file be loaded when running unit tests?
我正在运行单元测试作为 ASP.NET Core MVC 解决方案的一部分。 .NET Core 的版本准确地说是 2.1。
我在 launchSettings.json 文件中创建了一个配置文件部分,其中包含我希望由测试运行程序加载和注入的环境变量,以便在运行单元测试时环境变量可用并且可以包含特定值。
我的 ASP.NET Core MVC 项目中的 launchSettings.json 作为链接添加到我的单元测试项目中,并且属性设置为 Build Action - None,Copy to output folder - Copy Always。
该文件被复制到我的输出文件夹中,但我不确定如何让测试运行程序将此文件与 UnitTesting 配置文件一起使用。 我曾尝试使用“测试”一词作为配置文件名称,但似乎没有任何效果。
这是一个示例 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}"
}
}
}
}
我知道默认情况下,git 中会忽略 launchSettings.json 文件。 我们将使用此文件的开发版本检入我们的代码,该文件将包含预期在开发环境中可用的设置示例。
感谢您抽出时间阅读本文并提供帮助!
我现在写了这个静态加载器,但这并不理想:
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);
}
}
}
}
}
我创建了一个可以帮助您的包: https : //www.nuget.org/packages/DotNet.Project.LaunchSettings
你可以在这里找到源: https : //github.com/andygjp/DotNet.Project.LaunchSettings
我有一个与您类似的用例 - 我想测试不同的环境,我将这些环境的登录详细信息保存在 launchSettings.json 中。
这是我如何使用它:
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
}
它假设 launchSettings.json 位于通常的位置:
MyProject -> 属性 -> launchSettings.json
但是,如果您觉得它有用,我可以添加从指定文件路径加载启动设置的功能。
上面的示例使用它找到的第一个配置文件,但是,您也可以使用特定的配置文件。
希望能帮助到你。
对于 mstest 或 xunittest,在单元测试中使用环境变量的另一种解决方案是通过为平台提供的“.runsettings”文件:
请参阅以下链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.