Improve conversion error messages

When a conversion to an enum fails, list all the valid enum values in the error message.

Message before this commit:
> Error: heimday is not a valid value for DayOfWeek.

Message after this commit:
> Error: Failed to convert 'heimday' to DayOfWeek. Valid values are 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
This commit is contained in:
Cédric Luthi
2023-01-24 19:38:03 +01:00
parent 7b9553dd22
commit de847b90e4
8 changed files with 83 additions and 10 deletions

View File

@ -29,5 +29,52 @@ public sealed partial class CommandAppTests
cat.Agility.ShouldBe(6);
});
}
[Fact]
public void Should_Convert_Enum_Ignoring_Case()
{
// Given
var app = new CommandAppTester();
app.Configure(config =>
{
config.AddCommand<HorseCommand>("horse");
});
// When
var result = app.Run(new[] { "horse", "--day", "friday" });
// Then
result.ExitCode.ShouldBe(0);
result.Settings.ShouldBeOfType<HorseSettings>().And(horse =>
{
horse.Day.ShouldBe(DayOfWeek.Friday);
});
}
[Fact]
public void Should_List_All_Valid_Enum_Values_On_Conversion_Error()
{
// Given
var app = new CommandAppTester();
app.Configure(config =>
{
config.AddCommand<HorseCommand>("horse");
});
// When
var result = app.Run(new[] { "horse", "--day", "heimday" });
// Then
result.ExitCode.ShouldBe(-1);
result.Output.ShouldStartWith("Error");
result.Output.ShouldContain("heimday");
result.Output.ShouldContain(nameof(DayOfWeek.Sunday));
result.Output.ShouldContain(nameof(DayOfWeek.Monday));
result.Output.ShouldContain(nameof(DayOfWeek.Tuesday));
result.Output.ShouldContain(nameof(DayOfWeek.Wednesday));
result.Output.ShouldContain(nameof(DayOfWeek.Thursday));
result.Output.ShouldContain(nameof(DayOfWeek.Friday));
result.Output.ShouldContain(nameof(DayOfWeek.Saturday));
}
}
}