Reputation: 9295
I want to test that a delegate does not throw FooException
, but I don't care if it throws anything else. Therefore I can't use the Nothing
constraint.
The constraints model doesn't have something like this:
Assert.That(del, Throws.Not.InstanceOf<FooException>()); //can't use Not like this
Is that possible somehow?
Upvotes: 2
Views: 369
Reputation: 13736
This is slightly awkward but should do it
Assert.That(Assert.Catch(del), Is.Null.Or.Not.TypeOf<FooException>());
Personally, I prefer the two-line version
var ex = Assert.Catch(del);
Assert.That(ex, Is.Null.Or.Not.TypeOf<FooException>());
or the even clearer three-liner
var ex = Assert.Catch(del);
if (ex != null)
Assert.That(ex, Is.Not.TypeOf<FooException>());
This works because not asserting at all is the same as succeeding.
The lack of a more direct way to test this in the syntax reflects an opinion of the developers - at least at the time - that you should always know what exception you are expecting.
Upvotes: 3
Reputation: 2266
Looks like nunit does not provide it out of the box.
But you have some workarounds:
You may use additional assertion framework, like FluentAssertions
,
which allows you to do next assertion:
del.ShouldNotThrow<FooException>();
Also you can write your own custom-constraints, like ThrowsNothingConstraint
Or you can just write custom metod
public void AssertException<T>(Action act) where T : Exception
{
try
{
act();
}
catch (T e)
{
Assert.Fail();
}
catch (Exception e)
{
Assert.Pass();
}
}
Upvotes: 3