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

查看:1446
本文介绍了如何使用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"));

您还可以使用流利的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天全站免登陆