Skip to content

Testing your app#

Traditionally, one of the problems with writing console apps is automated testing of the apps. CommandDotNet solves this with our Test Tools.

We make it easy to test your app as if you're entering the commands in the console.

The first step is to get access to the AppRunner the program is using so your tests are testing the application as it is configured.

Let's extract the configuration into a public static property

static int Main(string[] args) => AppRunner.Run(args);

public static AppRunner AppRunner => new AppRunner<Program>();
snippet source | anchor

Now the tests can use Program.AppRunner for all tests.

The second step is to use IConsole to capture the output for assertions in tests.

public void Add(IConsole console, int x, int y) => console.WriteLine(x + y);

public void Subtract(IConsole console, int x, int y) => console.WriteLine(x - y);
snippet source | anchor

IConsole is one of the default types that can be injected into command methods. Read more about the other available types in here

Alternatively, or if there is code writing to System.Console that you cannot migrate to IConsole, configure the AppRunner with InterceptSystemConsoleWrites()

public static AppRunner AppRunner =>
    new AppRunner<Program>()
        .InterceptSystemConsoleWrites();
snippet source | anchor

Testing#

CommandDotNet supports two different test patterns:

Standard#

[Test]
public void Given2Numbers_Should_OutputSum()
{
    var result = Program.AppRunner.RunInMem("Add 40 20");
    result.ExitCode.Should().Be(0);
    result.Console.OutText().Should().Be("60");
}
snippet source | anchor

BDD Style#

BDD follows the Given / When / Then style. Configuration of the AppRunner is the given, and the framework handles the when and then.

[Test]
public void Given2Numbers_Should_OutputSum() =>
    Program.AppRunner.Verify(new Scenario
    {
        When = { Args = "Add 40 20" },
        Then = { Output = "60" }
    });

[Test]
public void GivenANonNumber_Should_OutputValidationError() =>
    Program.AppRunner.Verify(new Scenario
    {
        When = { Args = "Add a 20" },
        Then =
        {
            ExitCode = 2, // validations exit code = 2
            Output = "'a' is not a valid Number"
        }
    });
snippet source | anchor

See Test Tools in the Testing help section for more, such as testing prompts and piped input.