Search Results for

    Show / Hide Table of Contents

    Assert.ThrowsAsync

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

    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.

    [TestFixture]
    public class AssertThrowsTests
    {
        [Test]
        public void Tests()
        {
            // Using a method as a delegate
            Assert.ThrowsAsync<ArgumentException>(async () => await MethodThatThrows());
        }
    
        private async Task MethodThatThrows()
        {
            await Task.Delay(100);
            throw new ArgumentException();
        }
    }
    

    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.

    [TestFixture]
    public class UsingReturnValue
    {
        [Test]
        public void TestException()
        {
            MyException ex = Assert.ThrowsAsync<MyException>(async () => await MethodThatThrows());
    
            Assert.That(ex.Message, Is.EqualTo("message"));
            Assert.That(ex.MyParam, Is.EqualTo(42));
        }
    
        private async Task MethodThatThrows()
        {
            await Task.Delay(100);
            throw new MyException("message", 42);
        }
    }
    

    See Also

    • Assert.Catch
    • Assert.CatchAsync
    • Assert.Throws
    • ThrowsConstraint
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0