在 MSTests 中是否可以捕获任何异常?

发布于 2024-08-19 15:53:29 字数 350 浏览 1 评论 0原文

我试图避免脆弱的测试。我想断言,当传入无效数据时,方法会引发异常,而且我不在乎是哪一个。

以 String.IsNullOrEmpty 为例,如果字符串为空,您不想抛出空引用异常,对吗?如果它是 null 你我想你可以抛出一个 argumentException 。我不认为为 null 和empty 设置单独的保护子句是一个好主意,而且无论如何我都希望能够断言我的单元抛出了异常。

使用 [ExpectedException(typeof(Exception))] 会给出错误,指出异常类型必须从异常继承。我的解决方案是一个 try/catch 块,如果没有抛出异常,则带有 Assert.Fail 。有更好/更干净的方法吗?

I am trying to avoid a brittle test. I'd like to assert that a method throws an exception when invalid data is passed in, and I don't care which one.

Take String.IsNullOrEmpty for instance, if the string is empty you don't want to throw a nullreference exception right? if it's null you I suppose you could throw an argumentException. I don't think having a seperate guard clause for null vs empty is a good idea, and regardless I'd like to be able to just assert that an exception is thrown from my unit.

using [ExpectedException(typeof(Exception))] gives an error saying the exception type must inherit from exception. My solution is a try/catch block with an Assert.Fail if no exception is thrown. Is there a better/cleaner way?

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

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

发布评论

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

评论(1

青衫负雪 2024-08-26 15:53:29

看起来尝试捕获是断言抛出通用异常的唯一选择。以下是 MSDN 上关于此主题的线程:

http://social.msdn.microsoft.com/Forums/en/vststest/thread/ed891a27-272c-4938-9a93-719c149d820e

我仍然质疑是否需要对通用异常进行断言。如果您正在测试特定场景,您应该知道应该抛出什么异常。对于使用 string.IsNullOrEmpty() 的示例,您似乎想要同时测试空字符串和空值。如果空字符串是无效输入,则抛出 ArgumentException 似乎是合理的,您可以针对特定异常进行测试。如果字符串是有效输入,那么您可以进行测试以确保它不会引发异常。

It looks like try-catching is your only option for asserting that a generic exception is thrown. Here is a thread on MSDN on this subject:

http://social.msdn.microsoft.com/Forums/en/vststest/thread/ed891a27-272c-4938-9a93-719c149d820e

I would still question the need for asserting on a generic exception. If you are testing for a specific scenario, you should know what exception should be thrown. For your example of using string.IsNullOrEmpty(), it seems like you want tests for both an empty string and a null value. If the empty string is invalid input, then throwing an ArgumentException seems reasonable and you can test against the specific exception. If the string is valid input, then you can test to make sure it does not thrown an exception.

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