繁体   English   中英

如何在单元测试中使用环境变量(.net core)

[英]How to use environment variables in unit tests (.net core)

我有一个方法,我正在尝试测试它使用我的“local.settings.json”中的环境变量

private static string _environmentVar = Environment.GetEnvironmentVariable("envirnomentVarConfig");

public string MyMethod()
{
    var result = DoStuff(_environmentVar)
    return result;  
}

在我的测试中,我调用了这个方法,在调试时,我可以看到 _environmentVar 为空。

我需要在测试中设置 envirnomentVarConfig 吗? 如果有怎么办?

通过在测试中设置变量来解决这个问题:

Environment.SetEnvironmentVariable("environmentVarConfig", "environmentVarValue");

您可以在.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>

根据文档https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0#set-the-environment ,我能够在全球范围内对 WebHostBuilder 进行测试

protected override IWebHostBuilder CreateWebHostBuilder() =>
       base.CreateWebHostBuilder().UseEnvironment("Testing");

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM