单元测试内部异常 [英] Unit testing for inner exceptions

查看:91
本文介绍了单元测试内部异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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:


  1. 自行实现

  2. 更改(或扩展)框架

我将从第二个解决方案开始。考虑使用 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.

这篇关于单元测试内部异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆