I have a controller method that throws a custom exception if a loop through a list of ids doesn’t find a specified id, otherwise it returns a partial view.
I’ve done the test to see if it successfully returns a partial view but how do I test that the method fails and that the custom exception is thrown?
You can do a simple try/catch and perform Assert.Fail if you don’t catch the expected exception. However, most unit testing frameworks provide an automated way of testing for exceptions.
Microsoft’s MSTest has the
ExpectedExceptionattribute which can be applied to a test method:If the test method above does NOT throw an ArgumentNullException, MSTest will mark the test as a fail.
NUnit has a more granular
Assert.Throwsthat gives you more specific control of exactly where in the test method an exception is expected.