Sam*_*vis 144 c# nunit unit-testing assert exception
我发现这些似乎是测试异常的两种主要方式:
Assert.Throws<Exception>(()=>MethodThatThrows());
[ExpectedException(typeof(Exception))]
Run Code Online (Sandbox Code Playgroud)
哪个最好?有人提供优势吗?或者仅仅是个人偏好的问题?
Ale*_*iuk 251
主要区别是:
ExpectedException()
如果在测试方法的任何位置发生异常,则属性使测试通过.
使用Assert.Throws()
允许指定exact
预期异常的代码的位置.
NUnit 3.0 ExpectedException
完全放弃了官方支持.
所以,我绝对更喜欢使用Assert.Throws()
方法而不是ExpectedException()
属性.
chu*_*e x 88
第一个允许您通过多个调用测试多个异常:
Assert.Throws(()=>MethodThatThrows());
Assert.Throws(()=>Method2ThatThrows());
Run Code Online (Sandbox Code Playgroud)
第二个只允许您测试每个测试函数的一个异常.
Mik*_*ill 35
我更喜欢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");
}
Run Code Online (Sandbox Code Playgroud)
Rev*_*nks 10
您也可以强力键入您期望的错误(如旧的attrib版本).
Assert.Throws<System.InvalidOperationException>(() => breakingAction())
Run Code Online (Sandbox Code Playgroud)