When to use Assert.Catch vs Assert.Throws in unit testing

I'm just looking for some examples of when it is advisable to use Assert.Catch or Assert.Throws to state any exceptions caused by unit testing. I know that I can use ExpectedException, but I'm curious to know the difference between "Catch" and "Throws" in particular. Thanks!

+7
c # unit-testing nunit
source share
1 answer

The first line of the document looks pretty clear:

Assert.Catch is similar to Assert.Throws , but will throw an exception that is thrown from the specified one.

Thus, use Assert.Catch if the exception obtained from the specified exception is valid (this means that it will also be caught in the equivalent catch ).

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 ); 
+9
source share

All Articles