'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?
Solution 1:[1]
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...
Solution 2:[2]
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
Solution 3:[3]
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"));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Svish |
| Solution 2 | |
| Solution 3 | Kornelis |
