Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Task .Should() extensions #1305

Closed
michal-ciechan opened this issue Apr 16, 2020 · 2 comments
Closed

New Task .Should() extensions #1305

michal-ciechan opened this issue Apr 16, 2020 · 2 comments

Comments

@michal-ciechan
Copy link
Contributor

michal-ciechan commented Apr 16, 2020

Wondering if it is worth adding the following 2 extension methods for Task/Task<T> to not need Func<Task> act = .... each time I want to assert the method call with throw an exception.

public static class FluentAssertionExtensions
{
    public static NonGenericAsyncFunctionAssertions Should(this Task task)
    {
        Func<Task> act = () => task;

        return act.Should();
    }

    public static GenericAsyncFunctionAssertions<T> Should<T>(this Task<T> task)
    {
        Func<Task<T>> act = () => task;

        return act.Should();
    }
}

I have been copying this code from project to project and sounds generic enough to be moved.

Probably would be best to create a TaskAssertions / GenericTaskAssertions which either inherit from or delegate to the corresponding [Non]GenericAsyncFunctionsAssertions on the ThrowsAsync etc.

If it is something you guys may be interested in adding let me know, I can create a PR.

This allows me to

[Fact]
public async Task Test()
{
    await _sut.AsyncMethod().Should().ThrowAsync<InvalidOperationException>();
}

Rather than

[Fact]
public async Task Test()
{
    Func<Task> act = () => _sut.AsyncMethod();

    await act.Should().ThrowAsync<InvalidOperationException>();
}
@michal-ciechan
Copy link
Contributor Author

Also worth considering ValueTask /ValueTask<T> pair. Delegate to ValueTask.AsTask(), and then continue as normal Task

@jnyrup
Copy link
Member

jnyrup commented Apr 16, 2020

The current stand is not to include those assertions.
See e.g. #1001, #1011, #1013 and https://fluentassertions.slack.com/archives/C039Y2H7U/p1581329945017800

But you can write it almost as concise as your desired example by using FluentActions.

using static FluentAssertions.FluentActions;

await Awaiting(() => _sut.AsyncMethod()).Should().ThrowAsync<InvalidOperationException>();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants