nunit / nunit

NUnit Framework
https://nunit.org/
MIT License
2.47k stars 723 forks source link

[question] Is there syntactic sugar for asserting the type of exception thrown? #4677

Closed Bartleby2718 closed 2 months ago

Bartleby2718 commented 2 months ago

As written in https://docs.nunit.org/articles/nunit/writing-tests/assertions/classic-assertions/Assert.DoesNotThrow.html, "Assert.DoesNotThrow verifies that the delegate provided as an argument does not throw an exception."

If you want to verify that the delegate does throw an exception (but don't want to verify its exception message), you need to do

Assert.That(Assert.Throws<TException>(myDelegate), Is.Not.Null);

which is wordier than its DoesNotThrow counterpart:

Assert.DoesNotThrow<TException>(myDelegate);

Do you have built-in syntactic sugar for Assert.That(Assert.Throws<TException>(myDelegate), Is.Not.Null);? If not, could you add one (and another for the async counterpart)?

mikkelbu commented 2 months ago

I might be overlooking something, but why do want to test that the result is not null? I would expect to get the same result from using Assert.Throws directly as it fails if the method doesn't throw the expected exception.

So if myDelegate throws TException, then both

Assert.Throws<TException>(myDelegate);

and

Assert.That(Assert.Throws<TException>(myDelegate), Is.Not.Null);

pass successfully.

If the delegate does not throw both fail with

  Expected: <TException>
  But was:  null

and if it is another type of exception both fail with

  Expected: <TException>
  But was:  <AnotherException>
Bartleby2718 commented 2 months ago

Welp, that's embarrassing. I completely confused how Assert.Throws worked. Thanks for the quick response!