Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 254
Johan Alkstål Avatar asked Jun 22 '26 10:06

Johan Alkstål


1 Answers

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.

like image 119
PatrickSteele Avatar answered Jun 28 '26 18:06

PatrickSteele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!