我有一些創建配置的代碼,添加一些環境變數,然后,如果它們存在,添加一些命令列引數。這里的目的是命令列引數可以覆寫環境變數。所以我想測驗一下,如果使用同名的環境變數和命令列 arg,命令列 arg 是否覆寫了環境變數。
這很可能適用于 uris 之類的東西。
所以我的代碼是這樣的:
public static DoSomeConfigStuff()
{
var builder = new ConfigurationBuilder();
builder.AddEnvironmentVariables();
var commandLineArgs = Environment.GetCommandLineArgs();
if(commandLineArgs != null)
{
builder.AddCommandLine(commandLineArgs);
}
var root = builder.build();
// set various uris using root.GetValue<string>("some uri name")
}
我想對此進行測驗,以便在提供命令列引數時使用它提供的 uri,特別是在它同時作為環境變數和命令列引數提供的情況下。有沒有辦法做到這一點?我讀到人們通過使用環境變數有效地模擬了命令列引數,但這在這里不起作用,因為我想在兩者都設定時進行測驗。
uj5u.com熱心網友回復:
你甚至需要這個邏輯嗎?只需無條件添加命令列引數,IConfiguration 將首先處理使用命令列引數,然后回退到環境變數。您實際上并不需要對此進行單元測驗,因為這是 ConfigurationBuilder 的功能,而不是您的代碼(但您可以根據需要對其進行測驗)。
var root = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddCommandLine(Environment.GetCommandLineArgs())
.Build();
如果確實需要這樣做,請將構建 IConfigurationRoot 與從環境中獲取資料分開。前一步可以進行單元測驗,后一步不需要:
// This method can be unit tested
IConfigurationRoot BuildConfiguration(string[] commandLineArgs)
{
var builder = new ConfigurationBuilder();
builder.AddEnvironmentVariables();
if (commandLineArgs != null)
{
builder.AddCommandLine(commandLineArgs);
}
return builder.Build()
}
// This method is NOT unit tested
public static DoSomeConfigStuff()
{
var root = BuildConfiguration(Environment.GetCommandLineArgs());
// set various uris using root.GetValue<string>("some uri name")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/385181.html
