Closed
Description
When using the Throws.Exception
constraint to test an async delegate with a return value, the test incorrectly fails even when an Exception should have been thrown:
[Test]
public void ThrowsExceptionConstraint_AsyncReturnValue_Fails()
{
Assert.That(async () => { await Task.Delay(200); throw new Exception(); return true; },
Throws.Exception);
}
Failed ThrowsExceptionConstraint_AsyncReturnValue_Fails
Error Message:
Expected: an exception to be thrown
But was: no exception thrown
The constraint appears to work fine for async delegates that return Task
instead of Task<T>
or if additional constraints are supplied.
[Test]
public void ThrowsExceptionConstraint_AsyncTask_Passes()
{
Assert.That(async () => { await Task.Delay(200); throw new Exception(); },
Throws.Exception);
// Passes
}
[Test]
public void ThrowsExceptionConstraint_AsyncReturnValue_AdditionalConstraint_Passes()
{
Assert.That(async () => { await Task.Delay(200); throw new Exception("foo"); },
Throws.Exception.Message.Contains("foo"));
// Passes
}
I'm aware that it is not recommended to use the Throws.Exception
constraint on its own. However, it's not completely uncommon, and the false test failure is pretty misleading.
I've reproduced this on:
- NUnit versions: 3.11.0, 3.10.1
- Test runners: nunit3-console v3.9.0, ReSharper 2018.1.2
- .NET versions: Core 2.0, Core 2.1, Framework 4.6.1