C#、NUnit:测试 ArgumentException 是否具有正确 ParamName 的清晰方法

发布于 2024-08-17 09:54:22 字数 261 浏览 1 评论 0原文

要测试某些东西是否会抛出ArgumentException,我可以这样做:

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

How can I check that the ParamName is Correct in a clear way?还有额外的问题:或者您可能会建议根本不测试这个?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

玩套路吗 2024-08-24 09:54:22

找到了一种非常清晰的方法(但如果有人有更好的方法,请告诉我!)

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

Facepalm< /a>...

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

家住魔仙堡 2024-08-24 09:54:22

如果您想对异常执行更多操作,而不仅仅是断言抛出该异常,则 Assert.Throws 实际上会返回该异常,您可以执行以下操作:

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

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
阳光的暖冬 2024-08-24 09:54:22

跳转到12年后的未来->你现在可以这样做(使用 NUnit 3 的流利语法):

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

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

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"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文