NUnit:Assert.Throws [英] NUnit: 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.
推荐答案
code> 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"));
当异常消息断言时,有一点小提示是使用 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.
这篇关于NUnit:Assert.Throws的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!