TUnit
TUnit copied to clipboard
Add `OnlyIf` method for throw assertions
I often have the issue that I want to assert in a test, that an exception was only thrown when a certain condition applies. Currently I have to introduce an if/else clause, e.g.
if (expectMatch)
{
await Assert.That(sut).ThrowsNothing();
}
else
{
await Assert.That(sut).ThrowsException().WithMessageMatching(expectedExpression);
}
This PR adds an OnlyIf
method to the ThrowsException
class, so that this can be simplified to
await Assert.That(sut).ThrowsException().WithMessageMatching(expectedExpression).OnlyIf(!expectMatch);
The OnlyIf
will check the predicate, and if it is true
it will ensure, that the exception was thrown as specified. If it is false
, it will instead ensure, that no exception was thrown.