使用NUnit Assert.Throws方法或ExpectedException属性?
我发现这些似乎是异常测试的两种主要方式:
Assert.Throws<Exception>(()=>MethodThatThrows());
[ExpectedException(typeof(Exception))]
哪个最好? 一个人比另一个人有优势吗? 还是仅仅是个人喜好的问题?
第一个允许您测试多个异常,并有多个调用:
Assert.Throws(()=>MethodThatThrows());
Assert.Throws(()=>Method2ThatThrows());
第二个只允许您测试每个测试功能的一个异常。
主要区别是:
如果异常发生在测试方法的任何地方, ExpectedException()
属性使测试通过。
Assert.Throws()
的使用允许指定预期异常的代码的exact
位置。
NUnit 3.0完全放弃了对ExpectedException
官方支持。
所以,我绝对更喜欢使用Assert.Throws()
方法而不是ExpectedException()
属性。
我更喜欢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");
}
链接地址: http://www.djcxy.com/p/73383.html
上一篇: Use NUnit Assert.Throws method or ExpectedException attribute?