Reputation: 2567
I developed an extension method with the signature void ThrowIfAny<T>(this IEnumerable<T> e, Func<T, bool> f)
and I'm unit testing it. Logically, one of the tests is to check that does not throw. I know that I can write this assert like this:
Assert.DoesNotThrow(() => anEnum.ThrowIfAny(t => false));
However, I'm using constraint based assertions for the rest of my unit tests, and I'd like to know if this assert can be written using this style, maybe something like this (it doesn't compile):
Assert.That(() => anEnum.ThrowIfAny(t => false), Does.Not.Throw);
Upvotes: 1
Views: 615
Reputation: 2343
This should do it:
Assert.That(() => anEnum.ThrowIfAny(t => false), Throws.Nothing);
Upvotes: 4
Reputation: 7546
You basically need to write extensions that help you do this. I usually write multiple Assert extensions using CAssert name:
public static class CAssert
{
public static void That(Action action, MyTestSuit suit)
{
try
{
action();
if(suit.ShouldThrow)
{
Assert.Fail("Not thrown any exception but expected to.")
}
}
catch(Exception e)
{
if(suit.ShouldNotThrow)
{
Assert.Fail("Exception was thrown but not expected.")
}
}
}
}
Test suits is basically a set of options. It is mostly singletons. You can overload it's operators however you like, for example to combine options from different suits:
CAssert.That(()=> 1/0, Throws.Error<DivideByZeroException>() | Throws.Error<ArithmeticException>());
Upvotes: 0