Asserting Async Methods Throw Exceptions with FluentAssertions
By Harry Bellamy
- 1 minutes read - 98 wordsI always forget the syntax when verifying that async methods throw a particular exception with FluentAssertions. This post is to help me (and hopefully others) quickly find the solution to this slightly un-intuitive syntax.
Below is an outline of a test that would perform this verification with FluentAssertions and xUnit.
using FluentAssertions;
using System;
using System.Threading.Tasks;
using xUnit;
public class MyTestClass
{
[Fact]
public async Task AsyncExceptionTest()
{
var service = new MyService();
Func<Task> act = async () => { await service.MethodThatThrows(); };
await act.Should().ThrowAsync<InvalidOperationException>();
}
}
You can find out more about asserting exceptions with FluentAssertions here.