chobo2
chobo2

Reputation: 85765

How to do exception handling with nunit and moq?

I am trying to use nunits new way of exception handling but I am finding it hard to find information on it and how to also use it with moq.

I have right now moq that throws a exception on a mocked method but I don't know how to use nunit to catch it and look at it.

Upvotes: 5

Views: 3365

Answers (3)

Mark Simpson
Mark Simpson

Reputation: 23365

There's a few different ways to do it; I use Assert.Throws.

var exception = Assert.Throws<YourTypeOfException>(()=> Action goes here);

e.g.

var exception = Assert
                .Throws<ArgumentNullException>(()=> new ChimpPuncher(null));

You can then query the exception object further if you want, e.g.

Assert.That(exception.Message, Text.Contains("paramname");

Upvotes: 14

giri77
giri77

Reputation: 71

Best way to mention is: [ExpectedException(typeof(ApplicationException))] above the test method.

Upvotes: 2

David Andres
David Andres

Reputation: 31781

Why can't you enclose the mocked method call in a try/catch block and catch the specific exception being thrown?

Upvotes: 0

Related Questions