fluentassertions.analyzers icon indicating copy to clipboard operation
fluentassertions.analyzers copied to clipboard

Request: Give diagnosis when ThrowAsync etc. is not awaited

Open JeppeSN opened this issue 1 year ago • 2 comments

Description

I find that the analyzers should warn people if they say .Should().ThrowAsync<>() and similar, without actually awaiting the task produced by Fluent Assertions.

Complete minimal example reproducing the issue

Consider this code to be tested:

public sealed class C {
    public Task DoWorkAsync() => Task.CompletedTask;
    public Task<int> RetrieveNumberAsync() => Task.FromResult(42);
}

Then consider this attempt at proving that the methods in C will throw:

    [Test]
    public void X() {
        var c = new C();

        c.Invoking(x => x.DoWorkAsync()).Should().ThrowExactlyAsync<InvalidOperationException>();

        c.Invoking(x => x.RetrieveNumberAsync()).Should().ThrowExactlyAsync<InvalidOperationException>();
    }

The problem here is that the test is green. The author of it might think he has written a valid test proving the methods throw.

Actual behavior:

I see no help from FluentAssertions.Analyzers.

Expected behavior:

It would be nice to have some kind of diagnosis from the analyzer saying this is not a good use of Fluent Assertions. It might suggest that the author turns the test method X into an async method, and then uses await in front of the two expression statements.

Of course, the author could do other things, including appending Wait() to the end of the expressions.

Versions

  • Which version of Fluent Assertions Analyzers are you using? 0.30.0
  • Which .NET runtime and version are you targeting? .NET 8

Additional Information

I have seen more than one developer falling in this trap.

In the examples, I used ThrowExactlyAsync<>(). But I think it could be many other methods:

  • .ThrowAsync<>
  • .NotThrowAsync
  • .NotThrowAsync<>
  • .ThrowExactlyAsync<>
  • .ThrowWithinAsync<>
  • .NotThrowAfterAsync
  • .CompleteWithinAsync
  • .NotCompleteWithinAsync

and possibly others.

A couple of years ago, an experienced Stack Overflow user posted the following question: https://stackoverflow.com/questions/70006484/

JeppeSN avatar Jan 29 '24 09:01 JeppeSN