Skip to content

Broken code snippet in documentation (Assertions > Extensibility > Chaining and Converting) #3605

@maximerety

Description

@maximerety

Description

In https://tunit.dev/docs/assertions/extensibility/extensibility-chaining-and-converting/#1-create-the-assertion-class, the proposed code snippet does not compile:

public class IsProblemDetailsAssertion : Assertion<ProblemDetails>
{
    public IsProblemDetailsAssertion(AssertionContext<HttpResponseMessage> context)
        : base(context.Map<ProblemDetails>(async response =>
        {
            var content = await response.Content.ReadFromJsonAsync<ProblemDetails>();

            if (content is null)
            {
                throw new InvalidOperationException("Response body is not Problem Details");
            }

            return content;
        }))
    {
    }

    // [skipped]
}

This snippet would require an overload of the AssertionContext's Map method with the following signature, which does not exist:

public AssertionContext<TNew?> Map<TNew>(Func<TValue?, Task<TNew?>> mapper)

Discussion

We do have the following MapAsync method which is pretty close, but it changes the source value type to Task<TNew?> which is not desired:

public AssertionContext<Task<TNew?>> MapAsync<TNew>(Func<TValue?, Task<TNew?>> mapper)

A possible (although ugly) workaround is to force running async code synchronously:

public class IsProblemDetailsAssertion : Assertion<ProblemDetails>
{
    public IsProblemDetailsAssertion(AssertionContext<HttpResponseMessage> context)
        : base(context.Map(response =>
        {
            var content = Task.Run(() => response?.Content.ReadFromJsonAsync<ProblemDetails>()).GetAwaiter().GetResult();

            if (content is null)
            {
                throw new InvalidOperationException("Response body is not Problem Details");
            }

            return content;
        }))
    {
    }
}

Would there be any cleaner way to perform async conversions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions