Unit tests for command/option parsing correctness in CLI app? #2552
-
Looking for advice and example code on how to add unit tests for CLI parsing correctness? Some way to provide a string, run parse on it, then test for success/failure and value presence, seems not too difficult, but is there a way to express the results in e.g. xUnit |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 10 replies
-
What I do is have a method that creates the parser data structures and takes in For example, something like: [Theory]
[InlineData("quiet", LogLevel.Quiet)]
[InlineData("detailed", LogLevel.Detailed)]
public async Task ValidateFooBarVerbosity(string input, LogLevel expected)
{
CliCommand parser = FooBarCommand.Create(ValidateArguments);
_ = await parser.Parse($"foo -v {input}").InvokeAsync();
async Task ValidateArguments(FooBarArguments args)
{
args.Verbosity.Should().Be(expected);
}
} Writing tests for error conditions is a bit different, instead of This way I can write many exhaustive tests for the CLI parsing, without it actually executing the product code, so it's nice and fast to execute and doesn't have side effects. |
Beta Was this translation helpful? Give feedback.
By calling
ParseResult.GetValue
(renamed in beta5 fromGetValueForArgument
/GetValueForOption
), you can check the parsed value of any option or argument.You can see lots of usage examples in these tests:
https://github.com/dotnet/command-line-api/blob/060374e56c1b2e741b6525ca8417006efb54fbd7/src/System.CommandLine.Tests/GetValueByNameParserTests.cs
https://github.com/dotnet/command-line-api/blob/e8282e765515d32c96ea6adb2ec83653ed1379a5/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs
This refers to the functionality in earlier versions that allowed System.CommandLine to create an instance of a class with propert…