Home > Mobile >  How can you test command line arguments used?
How can you test command line arguments used?

Time:12-14

I have some code that creates a configuration, adds some environment variables and then, if they exist, add some command line args. The purpose here is that a command line arg could override an environment variable. So I want to test that if an environment variable and command line arg of the same name are used, that the command line arg overrides the environment variable.

This would most likely be for things like uris and such.

So my code is something like this:

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")
}

I want to test this so that when a command line argument is supplied that the uri it has supplied is used, particularly in the situation that it's supplied both as an environment variable and a command line param. Is there anyway to do that? I read that people are effectively mocking command line params by using environment variables but that won't work here as I want to test when both are set.

CodePudding user response:

Do you even need this logic? Just add the command line arguments unconditionally, and the IConfiguration will take care of using command line arguments first, then fall back to environment variables. You don't really need to unit test this because this is a function of ConfigurationBuilder, not your code (but you can test it if you want).

var root = new ConfigurationBuilder()
  .AddEnvironmentVariables()
  .AddCommandLine(Environment.GetCommandLineArgs())
  .Build();

If you do need to do this, then separate building the IConfigurationRoot from getting the data from the environment. The former step can be unit tested, the latter does not need to be:

// 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")
}

  • Related