Async Unit Testing for Exceptions with Nunit
Regardless of the rights and wrongs — that’s for another day — I am now writing more async code than ever before. One of the first issues I came across with this was Unit Testing. I use Nunit and have been very happy with it and certainly see no reason to change so I looked at what Nunit had available for this.
Obviously async code can throw exceptions as easily as synchronous code and we may need to test for these. Here is the most simple example that I can come up with that works
[Test]
public async Task MethodAsync_Not_Implemented()
{
var MyApp= new Class(); Assert.ThrowsAsync<NotImplementedException>(() => MyApp.MyMethodAsync());
}
The key to this is the async Task in the method declaration and the Assert.ThrowsAsync method
In reality you may want to do more checks on the exception
[Test]
public async Task MethodAsync_Not_Implemented()
{
var MyApp= new Class(); var ex = Assert.ThrowsAsync<NotImplementedException>(() => MyApp.MyMethodAsync()); Assert.That(ex.Message, Is.EqualTo("message"));
Assert.That(ex.MyParam, Is.EqualTo(42));
}