我发现这些似乎是测试异常的两种主要方法:
Assert.Throws<Exception>(()=>MethodThatThrows());
[ExpectedException(typeof(Exception))]
其中哪一个最好?一个比另一个有优势吗?还是仅仅是个人喜好问题?
我发现这些似乎是测试异常的两种主要方法:
Assert.Throws<Exception>(()=>MethodThatThrows());
[ExpectedException(typeof(Exception))]
其中哪一个最好?一个比另一个有优势吗?还是仅仅是个人喜好问题?
主要区别在于:
ExpectedException()
如果测试方法中的任何地方发生异常,属性使测试通过。
的使用Assert.Throws()
允许指定exact
预期异常的代码位置。
NUnit 3.0 完全放弃了官方支持ExpectedException
。
所以,我绝对更喜欢使用Assert.Throws()
方法而不是ExpectedException()
属性。
第一个允许您通过多个调用测试多个异常:
Assert.Throws(()=>MethodThatThrows());
Assert.Throws(()=>Method2ThatThrows());
第二个只允许您为每个测试函数测试一个异常。
我更喜欢 assert.throws 因为它允许我在抛出异常后验证和断言其他条件。
[Test]
[Category("Slow")]
public void IsValidLogFileName_nullFileName_ThrowsExcpetion()
{
var a = new MyTestObject();
// 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");
}
您也可以强输入您期望的错误(如旧的属性版本)。
Assert.Throws<System.InvalidOperationException>(() => breakingAction())
如果您使用的是旧版本(<=2.0),NUnit
那么您需要使用ExpectedException
.
如果您使用的是2.5或更高版本,则可以使用Assert.Throw()
https://github.com/nunit/docs/wiki/Breaking-Changes
使用方法: https ://www.nunit.org/index.php?p=exceptionAsserts&r=2.5