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

When to use Assert.Catch versus Assert.Throws in Unit Testing

我只是在寻找一些示例,说明何时适合使用 Assert.Catch 或 Assert.Throws 断言单元测试中抛出的任何异常。我知道我也可以使用 ExpectedException,但我很想知道 "Catch" 和 "Throws" 之间的区别。谢谢!

documentation 的第一行看起来很清楚:

Assert.Catch is similar to Assert.Throws but will pass for an exception that is derived from the one specified.

所以使用 Assert.Catch 如果 从指定的异常派生 的异常是有效的(这意味着它也会在等效的 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);