NUnit 抛出的正确语法

Correct syntax for NUnit Throws

我需要编写一个测试来验证创建对象并传入空参数会抛出 ArgumentNullException

这是我的:

[Test]
public void ThrowsOnNullDependency()
{
    Assert.Throws(() => new FileService(null), Throws.Exception.TypeOf<ArgumentNullException>());
}

我遇到了以下异常。我见过几个不同的站点和 SO 答案,它们似乎都使用了 NUnit 的不同功能和语法。使用 NUnit3 检查是否抛出异常的正确方法是什么?

CS1503 Argument 2: cannot convert from 'NUnit.Framework.Constraints.ExactTypeConstraint' to 'NUnit.Framework.TestDelegate'

CS1660 Cannot convert lambda expression to type 'IResolveConstraint' because it is not a delegate type

如果您只是想检查是否抛出了异常,那么这些都可以:

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