我发现这似乎是测试异常的两种主要方式:
Assert.Throws<Exception>(()=>MethodThatThrows());
[ExpectedException(typeof(Exception))]
哪一个是最好的?其中一个是否提供了比另一个更好的优势?或者这仅仅是个人喜好的问题?
发布于 2013-02-22 07:59:53
第一个允许您使用多个调用测试多个异常:
Assert.Throws(()=>MethodThatThrows());
Assert.Throws(()=>Method2ThatThrows());
第二个函数只允许您为每个测试函数测试一个异常。
发布于 2013-02-22 08:02:51
我更喜欢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");
}
发布于 2015-11-24 20:23:41
你也可以强输入你期望的错误(就像旧的attrib版本一样)。
Assert.Throws<System.InvalidOperationException>(() => breakingAction())
https://stackoverflow.com/questions/15014461
复制相似问题