TUnit icon indicating copy to clipboard operation
TUnit copied to clipboard

Add `OnlyIf` method for throw assertions

Open vbreuss opened this issue 4 months ago • 2 comments

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.

vbreuss avatar Oct 12 '24 15:10 vbreuss