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

Lan*_*neL 9 c# nunit unit-testing

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

D S*_*ley 12

文档的第一行似乎很清楚:

Assert.Catch类似于Assert.Throws但会传递一个从指定的异常派生的异常.

因此,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 );
Run Code Online (Sandbox Code Playgroud)