nUnit中的ExpectedException给了我一个错误

Bas*_*ANI 38 .net c# testing nunit unit-testing

我刚接触.NET Framework上的测试工具,所以我在ReSharper的帮助下从NuGet下载了它.

我正在使用此快速入门来学习如何使用nUnit.我刚刚复制了代码,这个属性出现错误:

[ExpectedException(typeof(InsufficientFundsException))] //it is user defined Exception 
Run Code Online (Sandbox Code Playgroud)

错误是:

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

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

Pat*_*irk 67

如果您使用的是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);
}
Run Code Online (Sandbox Code Playgroud)

要将其更改为在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>());
}
Run Code Online (Sandbox Code Playgroud)


Nat*_*ith 12

不确定最近是否改变了但是它提供了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)); 
}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您仍想使用属性,请考虑以下事项:

[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));
}
Run Code Online (Sandbox Code Playgroud)