C# nUnit中的ExpectedException给了我一个错误

C# nUnit中的ExpectedException给了我一个错误,c#,.net,unit-testing,testing,nunit,C#,.net,Unit Testing,Testing,Nunit,我不熟悉在.NET Framework上使用测试工具,所以我在ReSharper的帮助下从NuGet下载了它 我用这个来学习如何使用nUnit。我刚刚复制了代码,在该属性上出现了一个错误: [ExpectedException(typeof(InsufficientFundsException))] //it is user defined Exception 错误是: 找不到类型或命名空间名称“ExpectedException” (是否缺少using指令或程序集引用?) 为什么??如果我

我不熟悉在.NET Framework上使用测试工具,所以我在ReSharper的帮助下从NuGet下载了它

我用这个来学习如何使用nUnit。我刚刚复制了代码,在该属性上出现了一个错误:

[ExpectedException(typeof(InsufficientFundsException))] //it is user defined Exception 
错误是:

找不到类型或命名空间名称“ExpectedException” (是否缺少using指令或程序集引用?)


为什么??如果我需要这样的功能,我应该用什么替换它呢?

如果您使用的是NUnit 3.0,那么您的错误是因为
ExpectedExceptionAttribute
。您应该改为使用类似的构造

例如,您链接的教程包含以下测试:

[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>());
}
[测试]
资金不足的公共无效转让()
{
账户来源=新账户();
来源:矿床(200m);
账户目的地=新账户();
目的地.押金(150米);
断言(()=>来源.转移资金(目的地,3亿),
抛出.TypeOf());
}

< /代码> 如果您仍然想使用属性,请考虑如下:

[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));
}

不确定这是否最近发生了变化,但NUnit 3.4.0提供了
Assert.Throws

[测试]
资金不足的公共无效转让(){
账户来源=新账户();
来源:矿床(200m);
账户目的地=新账户();
目的地.押金(150米);
Assert.Throws(()=>source.TransferFunds(destination,300m));
}

显示了什么错误?错误是在nUnit还是IDE中显示的?我认为您的代码返回了一个异常,而这个异常并不是针对此的UnficificientFundsceptionTanks。然而,一个问题是,与以前基于属性的异常规范相比,该规范有什么优势?我不认为它增加了任何真正的好处,只会使代码更不可读。可读性是主观的(我更喜欢这种语法),但最大的优点是您可以精确地知道哪条语句引发了异常。使用该属性,如果设置代码抛出预期的异常,则测试通过。使用此语法,测试将失败。
[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)); 
}