C# 使用 NUnit Assert.Throws 方法或 ExpectedException 属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15014461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use NUnit Assert.Throws method or ExpectedException attribute?
提问by SamuelDavis
I have discovered that these seem to be the two main ways of testing for exceptions:
我发现这些似乎是测试异常的两种主要方法:
Assert.Throws<Exception>(()=>MethodThatThrows());
[ExpectedException(typeof(Exception))]
Which of these would be best? Does one offer advantages over the other? Or is it simply a matter of personal preference?
其中哪一个最好?一个比另一个有优势吗?或者这只是个人喜好的问题?
采纳答案by chue x
The first allows you to test for more than one exception, with multiple calls:
第一个允许您通过多次调用测试多个异常:
Assert.Throws(()=>MethodThatThrows());
Assert.Throws(()=>Method2ThatThrows());
The second only allows you to test for one exception per test function.
第二个只允许您为每个测试函数测试一个异常。
回答by Mike Parkhill
I prefer assert.throws since it allows me to verify and assert other conditions after the exception is thrown.
我更喜欢 assert.throws 因为它允许我在抛出异常后验证和断言其他条件。
[Test]
[Category("Slow")]
public void IsValidLogFileName_nullFileName_ThrowsExcpetion()
{
// the exception we expect thrown from the IsValidFileName method
var ex = Assert.Throws<ArgumentNullException>(() => a.IsValidLogFileName(""));
// now we can test the exception itself
Assert.That(ex.Message == "Blah");
}
回答by Alexander Stepaniuk
The main difference is:
主要区别在于:
ExpectedException()
attribute makes test passed if exception occurs in anyplace in the test method.
The usage of Assert.Throws()
allows to specify exact
place of the code where exception is expected.
ExpectedException()
如果测试方法中的任何地方发生异常,则属性使测试通过。
使用Assert.Throws()
允许指定exact
预期异常的代码位置。
NUnit 3.0 drops official support for ExpectedException
altogether.
NUnit 3.0ExpectedException
完全放弃了官方支持。
So, I definitely prefer to use Assert.Throws()
method rather than ExpectedException()
attribute.
所以,我绝对更喜欢使用Assert.Throws()
方法而不是ExpectedException()
属性。
回答by Reverend Sfinks
You may also strong type the error you're expecting (like the old attrib version).
您还可以强输入您期望的错误(如旧的 attrib 版本)。
Assert.Throws<System.InvalidOperationException>(() => breakingAction())
回答by Gireesh k
If you are using older version(<=2.0) of NUnit
then you need to use ExpectedException
.
如果您使用的是旧版本(<=2.0),NUnit
那么您需要使用ExpectedException
.
If you are using 2.5or later version then you can use Assert.Throw()
如果您使用的是2.5或更高版本,则可以使用Assert.Throw()
https://github.com/nunit/docs/wiki/Breaking-Changes
https://github.com/nunit/docs/wiki/Breaking-Changes
How to use: https://www.nunit.org/index.php?p=exceptionAsserts&r=2.5
使用方法:https: //www.nunit.org/index.php?p=exceptionAsserts&r=2.5