-
-
Notifications
You must be signed in to change notification settings - Fork 114
Asserting Result Objects
With the package FluentResults.Extensions.FluentAssertions you can assert result objects in an elegant way.
var actualResult = Result.Fail("Error 1");
actualResult.Should().BeFailure();
var actualResult = Result.Ok();
actualResult.Should().BeSuccess();
var actualResult = Result.Ok(1);
actualResult.Should().HaveValue(1);
var actualResult = Result.Ok(1);
actualResult.Should().HaveReason("Error 1");
actualResult.Should().HaveReason<CustomError>("Error 2");
actualResult.Should().HaveReason(new { ... });
If you don't set an ErrorMessageComparison
via parameter then the default comparison is used. The default comparison is set globally via FluentResultAssertionsConfig.ErrorMessageComparison
which is by default ErrorMessageComparisonLogics.Equal
. The comparison ErrorMessageComparisonLogics.ActualContainsExpected
which is the default comparison logic for FluentResults.Extensions.FluentAssertions
< v2.0 is also available and can be set globally or via parameter. If you need some another custom comparison logic feel free to set your own. The comparison is only a Func<string, string, bool> with the parameters actual error message and expected error message.
var actualResult = Result.Ok();
actualResult.Should().HaveReason("Error 1", ErrorMessageComparisonLogics.ActualContainsExpected);
With the That
property you switch to the reason context to assert the reason.
var actualResult = Result.Fail(new CustomError().WithMetadata("ErrorCode", "123"));
actualResult.Should().HaveReason("Error 1")
.That.HaveMetadata("ErrorCode", "123");
var actualResult = Result.Fail(new CustomError() { ErrorCode = "123" });
actualResult.Should().HaveReason("Error 1")
.That.Satisfy<CustomError>(r => r.ErrorCode.Should().Be("123"));
var actualResult = Result.Ok(1);
actualResult.Should().BeFailure()
.And.Satisfy(result => {
result.Errors.Should().ContainEquivalentOf(new Error("Error 1"));
});