How to do exception handling with nunit and moq?

2019-06-21 05:10发布

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.

3条回答
Root(大扎)
2楼-- · 2019-06-21 05:36

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

查看更多
家丑人穷心不美
3楼-- · 2019-06-21 05:46

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

查看更多
时光不老,我们不散
4楼-- · 2019-06-21 05:55

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");
查看更多
登录 后发表回答