Svish
Svish

Reputation: 158341

C#, NUnit: Clear way of testing that ArgumentException has correct ParamName

To test that something throws for example an ArgumentException I can do this:

Assert.Throws<ArgumentException>(() => dog.BarkAt(deafDog));

How can I check that the ParamName is correct in a clear way? And bonus question: Or would you perhaps perhaps recommend not testing this at all?

Upvotes: 7

Views: 868

Answers (3)

Kornelis
Kornelis

Reputation: 21

Skipping 12 years into the future -> you can now do it like this (using NUnit 3's fluent syntax):

TestDelegate testDelegate = () => dawg.BarkAt(xzibit);

Assert.That(testDelegate, Throws.ArgumentException.With.Property(nameof(ArgumentException.ParamName)).EqualTo("otherDawg"));

Upvotes: 0

Svish
Svish

Reputation: 158341

Found a pretty clear way (but please let me know if anyone have an even better one!)

var e = Assert.Throws<ArgumentException>(() => dog.BarkAt(deafDog));
Assert.That(e.ParamName, Is.EqualTo("otherDog"));

Facepalm...

Upvotes: 10

David M
David M

Reputation: 72930

If you want to do more with the exception than just assert that it is thrown, then Assert.Throws actually returns the exception and you can do this:

var exception = Assert.Throws<ArgumentException>(() => dog.BarkAt(deafDog));
// Assert something else about the exception

Upvotes: 4

Related Questions