单元测试内部异常

编程入门 行业动态 更新时间:2024-10-24 16:25:45
本文介绍了单元测试内部异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Visual Studio的集成框架编写一些单元测试。我需要编写一些测试用例,当引发适当的异常时这些测试用例通过。问题是我需要测试的异常是嵌套在更通用的异常中的内部异常。是否有一些简单的解决方案,或者我需要扩展整个功能。我目前正在使用[ExpectedException]属性,但是在这种情况下它不会做很多事情。

I am writing some unit tests using Visual Studio's integrated framework. I need to write some test cases which pass when a proper exception is thrown. The problem is that the exceptions i need to test for are inner exceptions nested in a more general one. Is there some easy solution or do I need to extend the whole functionality. I am currently using the [ExpectedException] attribute, but it wont do much good in such a situation.

我也很好奇,当我们使用[ExpectedException]时会发生什么在测试本身中也有一些断言逻辑。是对两个条件都进行了评估(抛出了异常并且Assert语句被证明是有效的)还是抛出了正确的异常之后立即通过了测试?

I am also curious what happens when we use [ExpectedException] while we also have some Assert logic in the test itself. Are both the conditions evaluated(exception was thrown and the Assert statement turned out to be valid) or the test passes immediately after the correct exception is thrown?

推荐答案

如果您的框架不支持自定义引发,则通常有两种选择:

If your framework doesn't support custom throwing, you usually have two choices:

  • 自行实现
  • 更改(或扩展)框架
  • 我将从第二个解决方案开始。考虑使用 FluentAssertions 库。它允许您执行以下操作:

    I'll start with second solution. Consider using FluentAssertions library. It allows you to do something like this:

    Action deleteUser = () => usersRepository.Delete(new User { Id = null }); deleteUser .ShouldThrow<UserNotFoundException>() .WithInnerException<ArgumentNullException>() .WithInnerMessage("User Id must have value");

    您仍将使用Visual Studio测试框架,只是您将拥有一个额外的库, -流利的断言。

    You will still use Visual Studio testing framework, just that you'll have one extra library for, well - fluent assertions.

    另一方面,首选方法还有很多工作,因为手动解决方案通常是这样:

    First choice on the other hand is a bit more work as it is usually the case with hand-rolled solutions:

    try { usersRepository.Delete(new User { Id = null }); Assert.Fail("Deleting user with null id should throw"); } catch (UserNotFoundException ue) { Assert.AreEqual(ue.InnerException.Message, "User Id must have value"); }

    您替换 ExpectedException 具有定义实际异常实例的自定义代码的属性。就像我说的,这需要更多的工作,但是可以解决问题。

    You replace ExpectedException attribute with custom code asserting actual exception instance. Like I said, it is more work but does the trick.

    更多推荐

    单元测试内部异常

    本文发布于:2023-10-31 05:03:15,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1545082.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:单元测试   异常

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!