Is there some Assert method which can be used for unit test on whether a method throws an exception? [duplicate]

梦想与她 提交于 2019-12-24 19:20:02

问题


In C#, I have a method which throws an exception when a certain condition is true. I am supposed to write a unit test method to verify that.

Since the method being tested doesn't return a boolean value, I can't use Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue method. Which assert method can I use? Thanks.


回答1:


Use Assert.Throws, like so:

var ex = Assert.Throws<ArgumentNullException>(() => My.Method(null));
Assert.Equals("foo", ex.ParamName);

This works in XUnit and in the later versions of MSTest (install MSTest as a NuGet package to get up-to-date versions)



来源:https://stackoverflow.com/questions/44316606/is-there-some-assert-method-which-can-be-used-for-unit-test-on-whether-a-method

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