Back to Nunit

Assert.ThrowsAsync

docs/articles/nunit/writing-tests/assertions/classic-assertions/Assert.ThrowsAsync.md

latest1.6 KB
Original Source

Assert.ThrowsAsync

The Assert.ThrowsAsync is the async equivalent to Assert.Throws for asynchronous code. See Assert.Throws for more information.

csharp
Exception Assert.ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code);
Exception Assert.ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code,
                             string message, params object[] params);

Exception Assert.ThrowsAsync(IResolveConstraint constraint, AsyncTestDelegate code);
Exception Assert.ThrowsAsync(IResolveConstraint constraint, AsyncTestDelegate code,
                             string message, params object[] params);

TActual Assert.ThrowsAsync<TActual>(AsyncTestDelegate code);
TActual Assert.ThrowsAsync<TActual>(AsyncTestDelegate code,
                                    string message, params object[] params);

In the above code AsyncTestDelegate is a delegate of the form Task AsyncTestDelegate(), which is used to execute the code in question. This will likely be a lambda expression.

The following example shows the most common way of writing tests.

[!code-csharpAssertThrowsAsync]

This example shows use of the return value to perform additional verification of the exception. Note that you do not need to await the result.

[!code-csharpAssertThrowsAsync]

See Also