何时在单元测试中使用Assert.Catch和Assert.Throws?

12

我正在寻找一些示例,以了解在单元测试中断言任何异常抛出时使用 Assert.Catch 或 Assert.Throws 是适当的情况。 我知道我也可以使用 ExpectedException,但我很好奇“Catch”和“Throws”之间的区别。 谢谢!

1个回答

18

这份文档的第一行看起来很清晰:

Assert.Catch类似于Assert.Throws,但会为派生自指定异常的异常通过测试。

因此,如果从指定异常中派生出的异常是有效的(也就是在等效的catch块中也会被捕获),则使用Assert.Catch

Assert.Throws的文档提供了两个示例:

// Require an ApplicationException - derived types fail!
Assert.Throws(typeof(ApplicationException), code);
Assert.Throws<ApplicationException>()(code);

// Allow both ApplicationException and any derived type
Assert.Throws(Is.InstanceOf(typeof(ApplicationException)), code);
Assert.Throws(Is.InstanceOf<ApplicationException>(), code);

// Allow both ApplicationException and any derived type
Assert.Catch<ApplicationException>(code);

// Allow any kind of exception
Assert.Catch(code);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接