Testing for exceptions in async methods
Other variation of usage ThrowAsync method:
await Should.ThrowAsync<Exception>(async () => await Fail());
With Fluent Assertions v5+ the code will be like :
ISubject sut = BuildSut();
//Act and Assert
Func<Task> sutMethod = async () => { await sut.SutMethod("whatEverArgument"); };
await sutMethod.Should().ThrowAsync<Exception>();
This should work.
You should use Func<Task>
instead of Action
:
[Test]
public void TestFail()
{
Func<Task> f = async () => { await Fail(); };
f.ShouldThrow<Exception>();
}
That will call the following extension which is used to verify asynchronous methods
public static ExceptionAssertions<TException> ShouldThrow<TException>(
this Func<Task> asyncAction, string because = "", params object[] becauseArgs)
where TException : Exception
Internally this method will run task returned by Func
and wait for it. Something like
try
{
Task.Run(asyncAction).Wait();
}
catch (Exception exception)
{
// get actual exception if it wrapped in AggregateException
}
Note that test itself is synchronous.