【问题标题】:How can you test command line arguments used?如何测试使用的命令行参数?
【发布时间】:2022-01-17 03:03:10
【问题描述】:

我有一些代码可以创建配置,添加一些环境变量,然后,如果它们存在,添加一些命令行参数。这里的目的是命令行 arg 可以覆盖环境变量。所以我想测试一下,如果使用同名的环境变量和命令行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,特别是在它作为环境变量和命令行参数提供的情况下。有没有办法做到这一点?我读到人们通过使用环境变量来有效地模拟命令行参数,但这在这里不起作用,因为我想在两者都设置时进行测试。

【问题讨论】:

    标签: c# unit-testing command-line-arguments


    【解决方案1】:

    你甚至需要这个逻辑吗?只需无条件地添加命令行参数,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")
    }
    
    

    【讨论】:

    • 谢谢斯蒂芬。您可能就在这里,实际上并不需要逻辑。那些过度思考它的场景之一。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    相关资源
    最近更新 更多