📅  最后修改于: 2023-12-03 15:33:15.090000             🧑  作者: Mango
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
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
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