📜  nunit 使用带有 throws 的异步方法 (1)

📅  最后修改于: 2023-12-03 15:33:15.090000             🧑  作者: Mango

Introduction to Using 'throws' with Async Methods in NUnit

In NUnit, we can use the 'throws' assertion to test whether a method throws an exception under certain conditions. This feature can also be used with async methods, but there are some nuances to keep in mind.

When working with async methods, we need to use the 'async Task' or 'async Task' return types, depending on whether or not the method returns a value. We also need to use the 'await' keyword to ensure that the method completes before we move on to the next line of code.

Let's say we have an async method called 'DoSomethingAsync' that throws an exception if a certain condition is not met:

public async Task DoSomethingAsync()
{
    if (someConditionIsNotMet)
    {
        throw new Exception("Condition not met");
    }

    // method continues here
}

To test that this method throws an exception when the condition is not met, we can use the 'throws' assertion in NUnit:

[Test]
public async Task TestDoSomethingAsyncThrowsException()
{
    // arrange
    var myClass = new MyClass();

    // act and assert
    Assert.ThrowsAsync<Exception>(() => myClass.DoSomethingAsync());
}

Note that we use the 'Assert.ThrowsAsync' assertion instead of the regular 'Assert.Throws' assertion. We also pass in a lambda expression that calls the async method.

If the method throws an exception, the test will pass. If the method does not throw an exception, the test will fail. We can also further customize our assertion by specifying the exact exception message we expect to be thrown:

[Test]
public async Task TestDoSomethingAsyncThrowsExceptionWithCorrectMessage()
{
    // arrange
    var myClass = new MyClass();

    // act and assert
    var ex = 
        Assert.ThrowsAsync<Exception>(
            () => myClass.DoSomethingAsync());

    Assert.That(
        ex.Message, 
        Is.EqualTo("Condition not met"));
}

This test will also pass if the exception is thrown with the correct message.

In conclusion, we can use the 'throws' assertion in NUnit to test async methods that throw exceptions. We need to use the 'async Task' or 'async Task' return types, use the 'await' keyword, and use the 'Assert.ThrowsAsync' assertion. We can also further customize our assertion to test for specific exception messages.