Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm just looking for some examples of when it is appropriate to use Assert.Catch or Assert.Throws for asserting any exceptions thrown in unit testing. I know that I can use ExpectedException as well but I'm curious to know the difference between "Catch" and "Throws" in particular. Thanks!

like image 846
LaneL Avatar asked Aug 12 '15 17:08

LaneL


1 Answers

The first line of the documentation seems pretty clear:

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

So use Assert.Catch if an exception that derives from the specified exception is valid (meaning that it too would be caught in an equivalent catch block).

The documentation for Assert.Throws provides examples of both:

// 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);
like image 187
D Stanley Avatar answered Oct 10 '22 15:10

D Stanley