LaneL
LaneL

Reputation: 778

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!

Upvotes: 13

Views: 9865

Answers (1)

D Stanley
D Stanley

Reputation: 152556

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);

Upvotes: 20

Related Questions