How to do exception handling with nunit and moq?

此生再无相见时 提交于 2019-12-23 11:55:18

问题


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.


回答1:


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");



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/1386421/how-to-do-exception-handling-with-nunit-and-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!