簡體   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