开发者

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

开发者 https://www.devze.com 2022-12-15 20:59 出处:网络
To test that something throws for example an ArgumentException I can do this: Assert.Throws<ArgumentException>(() => dog.BarkAt(deafDog));

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 c开发者_如何学Golear way? And bonus question: Or would you perhaps perhaps recommend not testing this at all?


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...


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


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"));
0

精彩评论

暂无评论...
验证码 换一张
取 消