Reputation: 5347
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?
Upvotes: 2
Views: 3585
Reputation: 14697
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 ExpectedException
attribute which can be applied to a test method:
[ExpectedException(typeof(ArgumentNullException))]
[TestMethod]
public void DoSomething()
{ ... }
If the test method above does NOT throw an ArgumentNullException, MSTest will mark the test as a fail.
NUnit has a more granular Assert.Throws
that gives you more specific control of exactly where in the test method an exception is expected.
Upvotes: 10