gpt4 book ai didi

c# - NUnit 抛出的正确语法

转载 作者:行者123 更新时间:2023-12-01 22:25:21 32 4
gpt4 key购买 nike

我需要编写一个测试来验证创建对象并传入 null 参数是否会抛出 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>());

关于c# - NUnit 抛出的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35734000/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com