正确的NUnit抛出语法

时间:2016-03-01 21:35:13

标签: c# .net nunit

我需要编写一个测试来验证创建一个对象并传入null参数会抛出一个[Test] public void ThrowsOnNullDependency() { Assert.Throws(() => new FileService(null), Throws.Exception.TypeOf<ArgumentNullException>()); }

这就是我所拥有的:

window

我得到以下例外情况。我已经看到了一些不同的网站和SO答案,它们似乎都使用了NUnit的不同功能和语法。使用NUnit3检查是否有异常抛出异常的正确方法是什么?

  

CS1503参数2:无法转换为NUnit.Framework.Constraints.ExactTypeConstraint&#39;到&Nbspit.Framework.TestDelegate&#39;

     

CS1660无法将lambda表达式转换为&#39; IResolveConstraint&#39;因为它不是委托类型

1 个答案:

答案 0 :(得分:3)

如果您只是想检查是否抛出异常,那么其中任何一个都可以工作:

Assert.Throws<ArgumentNullException>(() => new FileService(null));

Assert.Throws(typeof(ArgumentNullException), () => new FileService(null));

如果您确实想使用ThrowsConstraint for more control over the check,那么当您使用带有约束的Assert.That时,语法就是这样:

Assert.That(() => new FileService(null), Throws.TypeOf<ArgumentNullException>());