似乎是一个非常微不足道的问题,但令我惊讶的是,我在网络上发现没有提及这一点。
我有一个 Nunit 测试项目(其他人写的,我不想改变太多),我需要调试。这些测试取决于他们使用
Environment.GetEnvironmentVariable
读取的环境变量。
我的问题是:在 Visual Studio 中调试测试时有没有办法可以传递环境变量?
我知道当我通过 Project Properties->Debug 调试可执行项目时可以传递环境变量,但这在运行测试时不会生效(例如通过 Test Explorer)。我还知道我可以通过
.runsettings
文件传递测试参数,但这些参数只能通过 TestContext
类访问。
我也知道我可以通过 .runsettings 文件传递测试参数,但这些参数只能通过 TestContext 类访问。
您还可以在.runsettings
文件中
指定环境变量:
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<RunConfiguration>
<EnvironmentVariables>
<YOUR_VARIABLE>Value for your variable</YOUR_VARIABLE>
<SOME_OTHER_VARIABLE>With another Value</SOME_OTHER_VARIABLE>
</EnvironmentVariables>
</RunConfiguration>
</RunSettings>
或者(如果您需要运行代码或计算值),您可以实现一个
DataCollector
,它通过ITestExecutionEnvironmentSpecifier
提供环境变量
// Add a reference to nuget package `Microsoft.TestPlatform.ObjectModel`
// The assembly name must end with `Collector` (i.e. match `*collector.dll`)
[DataCollectorFriendlyName("my own example collector")]
[DataCollectorTypeUri("datacollector://myown/examplecollector/1.0")]
public class MyDataCollector : DataCollector, ITestExecutionEnvironmentSpecifier
{
public override void Initialize(
XmlElement configurationElement,
DataCollectionEvents events,
DataCollectionSink dataSink,
DataCollectionLogger logger,
DataCollectionEnvironmentContext environmentContext)
{
// inspect configurationElement for your custom settings
}
public IEnumerable<KeyValuePair<string, string>> GetTestExecutionEnvironmentVariables()
{
return new Dictionary<string, string>
{
["YOUR_VARIABLE"] = "your value",
};
}
}
您还可以通过
.runsettings
文件配置数据收集器:
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<RunConfiguration>
<TestAdaptersPaths>path/where/to/find/your/collector</TestAdaptersPaths>
</RunConfiguration>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="my own example collector" uri="datacollector://myown/examplecollector/1.0">
<Configuration>
<SomeSettingHere/>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>
在 Visual Studio 2022 中,我只能在调试菜单中设置 2 个环境变量,而在 Visual Studio 2019 中,我们可以扩展到最多 3 个,任何人都可以建议如何实现相同的功能吗?
如果你想在调试项目时更改可用的环境而不破坏它,可以尝试在系统环境变量中设置它。
1),创建一个名为
number
的系统环境变量
2) 在您的代码中使用它:
string str= Environment.GetEnvironmentVariable("number",EnvironmentVariableTarget.Machine);
它将在您的代码中获取系统环境变量
number
。
3)开始调试这个项目并在其上设置断点,当你想更改变量时,可以直接在计算机属性下更改系统环境变量
number
上的值。
之后,只需将光标移回代码行,即可使用更改后的值。
============================================
更新1
当您更改系统变量
number
的值时,应单击OK
保存新值。然后将断点处的光标移回即可得到新值。
此外,您应该启用编辑并继续选项。