Johan Alkstål
Johan Alkstål

Reputation: 5347

Moq - Testing that a controller method throws an exception

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

Answers (1)

PatrickSteele
PatrickSteele

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

Related Questions