如何使用 Assert.Throws 来断言异常的类型? [英] How do I use Assert.Throws to assert the type of the exception?

查看:42
本文介绍了如何使用 Assert.Throws 来断言异常的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用 Assert.Throws 来断言异常的类型和实际的消息措辞?

How do I use Assert.Throws to assert the type of the exception and the actual message wording?

像这样:

Assert.Throws<Exception>(
    ()=>user.MakeUserActive()).WithMessage("Actual exception message")

我正在测试的方法抛出多个相同类型的消息,带有不同的消息,我需要一种方法来测试根据上下文抛出正确的消息.

The method I am testing throws multiple messages of the same type, with different messages, and I need a way to test that the correct message is thrown depending on the context.

推荐答案

Assert.Throws 返回抛出的异常,让您可以对异常进行断言.

Assert.Throws returns the exception that's thrown which lets you assert on the exception.

var ex = Assert.Throws<Exception>(() => user.MakeUserActive());
Assert.That(ex.Message, Is.EqualTo("Actual exception message"));

因此,如果没有抛出异常,或者抛出了错误类型的异常,第一个 Assert.Throws 断言将失败.但是,如果抛出了正确类型的异常,那么您现在可以对保存在变量中的实际异常进行断言.

So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert.Throws assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.

通过使用此模式,您可以对异常消息以外的其他内容进行断言,例如在 ArgumentException 和派生类的情况下,您可以断言参数名称是正确的:

By using this pattern you can assert on other things than the exception message, e.g. in the case of ArgumentException and derivatives, you can assert that the parameter name is correct:

var ex = Assert.Throws<ArgumentNullException>(() => foo.Bar(null));
Assert.That(ex.ParamName, Is.EqualTo("bar"));

您还可以使用 fluent API 来执行这些断言:

You can also use the fluent API for doing these asserts:

Assert.That(() => foo.Bar(null), 
Throws.Exception
  .TypeOf<ArgumentNullException>()
  .With.Property("ParamName")
  .EqualTo("bar"));

或者替代

Assert.That(
    Assert.Throws<ArgumentNullException>(() =>
        foo.Bar(null)
    .ParamName,
Is.EqualTo("bar"));

对异常消息进行断言时的一个小技巧是使用 SetCultureAttribute 修饰测试方法,以确保抛出的消息使用预期的区域性.如果您将异常消息存储为资源以允许本地化,这就会发挥作用.

A little tip when asserting on exception messages is to decorate the test method with the SetCultureAttribute to make sure that the thrown message is using the expected culture. This comes into play if you store your exception messages as resources to allow for localization.

这篇关于如何使用 Assert.Throws 来断言异常的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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