timmkrause
timmkrause

Reputation: 3621

FluentAssertions: How to break through drill-down of Which/And cascades?

Is there a way in FluentAssertions to avoid the automatic object graph drilldown for .And and .Which cascades? And some point of the drilldown I would like to go back to the root level and check the status code.

Small code example:

    Func<Task> action = async () => await this.someContext.someResponseTask;

    action.Should()
        .Throw<SwaggerOpenApiException<IList<ApiValidationError>>>()
        .Which.Result.Should().Contain(x => x.ErrorCode == errorCode)
        .Which.ErrorDetails.Should().Contain(dictionaryWithParsedErrorDetails)

        // NOTE: This does not work (compile) as it operates on "ErrorDetails",
        //       would like to access root level exception again.
        .Which.StatusCode.Should().Be(HttpStatusCode.Conflict);

Obviously I could wrap await this.someContext.someResponseTask into a try/catch and store the exception into a variable but this is not really an elegant way of doing this, especially with FluentAssertions at your fingertips.

Upvotes: 2

Views: 275

Answers (1)

timmkrause
timmkrause

Reputation: 3621

These were the 3 solutions I found which enable the traversal of separate paths of the object graph when dealing with an Exception.

The order represents the information richness of the summary in case of a failing test. So #3 for example where everything is put into one expression does not exactly tell you what failed.

The first item is very accurate.

1.

var exceptionAssertion = action.Should().Throw<SwaggerOpenApiException<IList<ApiValidationError>>>();

exceptionAssertion.Which.Result.Should().Contain(x => x.ErrorCode == errorCode);
exceptionAssertion.Which.StatusCode.Should().Be((int)HttpStatusCode.Conflict);

2.

// NOTE: This .Where is not LINQ, it's from FluentAssertions!
action.Should().Throw<SwaggerOpenApiException<IList<ApiValidationError>>>()
    .Where(e => e.Result.Any(r => r.ErrorCode == errorCode))
    .Where(e => e.StatusCode == (int)HttpStatusCode.Conflict);

3.

action.Should()
    .Throw<SwaggerOpenApiException<IList<ApiValidationError>>>()
    .Which.Should().Match<SwaggerOpenApiException<IList<ApiValidationError>>>(
        e =>
            e.Result.Any(r => r.ErrorCode == errorCode) &&
            e.StatusCode == (int)HttpStatusCode.Conflict);

Upvotes: 5

Related Questions