UnUnit中的ExpectedException给了我一个错误
本文关键字:一个 错误 中的 ExpectedException UnUnit | 更新日期: 2023-09-27 18:24:02
我是在.NET Framework上使用测试工具的新手,所以我在ReSharper的帮助下从NuGet下载了它。
我正在使用此快速入门来学习如何使用nUnit。我刚刚复制了代码,在这个属性上出现了一个错误:
[ExpectedException(typeof(InsufficientFundsException))] //it is user defined Exception
错误为:
未能找到类型或命名空间名称"ExpectedException"(您是否缺少使用指令或程序集引用?)
为什么?如果我需要这样的功能,我应该用什么来代替它?
如果您使用NUnit 3.0,那么您的错误是因为ExpectedExceptionAttribute
已被删除。您应该使用类似Throws Constraint的构造。
例如,您链接的教程有以下测试:
[Test]
[ExpectedException(typeof(InsufficientFundsException))]
public void TransferWithInsufficientFunds()
{
Account source = new Account();
source.Deposit(200m);
Account destination = new Account();
destination.Deposit(150m);
source.TransferFunds(destination, 300m);
}
要将其更改为在NUnit 3.0下工作,请将其更改如下:
[Test]
public void TransferWithInsufficientFunds()
{
Account source = new Account();
source.Deposit(200m);
Account destination = new Account();
destination.Deposit(150m);
Assert.That(() => source.TransferFunds(destination, 300m),
Throws.TypeOf<InsufficientFundsException>());
}
不确定最近是否发生了变化,但NUnit 3.4.0提供了Assert.Throws<T>
。
[Test]
public void TransferWithInsufficientFunds() {
Account source = new Account();
source.Deposit(200m);
Account destination = new Account();
destination.Deposit(150m);
Assert.Throws<InsufficientFundsException>(() => source.TransferFunds(destination, 300m));
}
如果您仍然想使用属性,请考虑以下内容:
[TestCase(null, typeof(ArgumentNullException))]
[TestCase("this is invalid", typeof(ArgumentException))]
public void SomeMethod_With_Invalid_Argument(string arg, Type expectedException)
{
Assert.Throws(expectedException, () => SomeMethod(arg));
}