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

Add async-support for WithMessage() #1052

Closed
mu88 opened this issue May 27, 2019 · 4 comments
Closed

Add async-support for WithMessage() #1052

mu88 opened this issue May 27, 2019 · 4 comments

Comments

@mu88
Copy link
Contributor

@mu88 mu88 commented May 27, 2019

Description

It would be great to use WithMessage() on ThrowAsync<>().

Complete minimal example reproducing the issue

// Arrange
Func<Task> act = () => throw new InvalidOperationException("Hello World");

// Act & Assert
await act().Should().ThrowAsync<InvalidOperationException>().WithMessage("HelloWorld");

Actual behavior:

Compile-time error. If have to await/block the Task to use WithMessage() (e. g. await act().Should().ThrowAsync<InvalidOperationException>().Result.WithMessage("HelloWorld");).

Versions

5.6.0

@jnyrup
Copy link
Member

@jnyrup jnyrup commented May 27, 2019

Currently you need to await the ThrowAsync before calling WithMessage.

(await act().Should().ThrowAsync<InvalidOperationException>()).WithMessage("HelloWorld");

note the extra parentheses.

To avoid those parentheses you could create an extension method like this

public static async Task<ExceptionAssertions<TException>> WithMessage<TException>(
    this Task<ExceptionAssertions<TException>> task,
    string expectedWildcardPattern,
    string because = "",
    params object[] becauseArgs)
    where TException : Exception
{
    return (await task).WithMessage(expectedWildcardPattern, because, becauseArgs);
}

and then call

await act().Should().ThrowAsync<InvalidOperationException>().WithMessage("HelloWorld");

@mu88
Copy link
Contributor Author

@mu88 mu88 commented May 27, 2019

Works like a charm! Is it okay for you if I provide this extension method as a PR?

@dennisdoomen
Copy link
Member

@dennisdoomen dennisdoomen commented May 27, 2019

Absolutely!

jnyrup added a commit that referenced this issue May 30, 2019
…#1055)

* Provide extension method 'WithMessage()' for async situations (#1052)

* Move method 'WithMessage()' away from dedicated partial and add documentation (#1052)

* Split into separate tests (#1052)
@jnyrup
Copy link
Member

@jnyrup jnyrup commented May 31, 2019

Contributed in #1055

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

Successfully merging a pull request may close this issue.

None yet
3 participants