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!
The first line of the documentation seems pretty clear:
Assert.Catch
is similar toAssert.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With