Inside a c# test I'm asserting with FluentAssertion. But, in this test, the "assert" only should be executed under a condition (when result is not valid)
This is my actual code:
if (!result.IsValid)
{
result
.Errors
.Should()
.Contain(e => e.ErrorMessage == MYERROR);
}
In my opinion, this code looks ugly, and I would like to rewrite in a more elegant way, something like this:
// -- DON'T COPY PASTE THIS CODE, IT DON'T COMPILE -- //
result
.Errors
.Should()
.When(!result.IsValid) //<-- something like this
.Contain(e => e.ErrorMessage == MYERROR);
// -- DON'T COPY PASTE THIS CODE, IT DON'T COMPILE -- //
Notice, in my sample, result
is a FluentValidation's ValidationResult
What would be the right syntax for this code. Maybe, this is an XY problem, and I'm focused on the wrong side of the issue.
The full test:
[Theory]
[InlineData("hola", true, "Its ok", null)]
[InlineData("hola\tadeu", false, "Not ok, contains a tab (no printable char)", MYERROR)]
public void OnlyPrintableCharsTest(string name, bool expected, string because, string? errorMsg)
{
// -- ARRANGE --
var persona =
new
Persona() { Name = nom };
// -- ACT --
var result =
MyCustomOnlyPrintableCharsValidator
.Validate(persona);
// -- ASSERT --
result
.IsValid
.Should()
.Be(expected, because);
if (!result.IsValid) // <-- Ugly code
{
result
.Errors
.Should()
.Contain(e => e.ErrorMessage == errMsg);
}
}
CodePudding user response:
You can choose to have a separate test for the positive (true) and negative (false) scenario.
From a unit testing best practices document from Microsoft:
If logic in your test seems unavoidable, consider splitting the test up into two or more different tests.
That also simplifies the InlineData
setup; the null
for errorMsg
in the positive scenario can be discarded.
Maybe you can switch to [Fact]
tests?