【问题标题】:ExpectedException in nUnit gave me an errornUnit 中的 ExpectedException 给了我一个错误
【发布时间】:2016-02-27 00:00:39
【问题描述】:

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

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

[ExpectedException(typeof(InsufficientFundsException))] //it is user defined Exception 

错误是:

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

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

【问题讨论】:

  • 显示什么错误?错误是否显示在 nUnit 或您的 IDE 中?
  • 我认为您的代码返回的异常不是 InsufficientFundsException

标签: c# .net unit-testing testing nunit


【解决方案1】:

如果您使用的是 NUnit 3.0,那么您的错误是因为 ExpectedExceptionAttribute has been removed。您应该改用 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>());
}

【讨论】:

  • 谢谢。但是,一个问题是,与以前的基于属性的异常规范相比,这有什么优势?我认为它不会增加任何真正的好处,只会使代码更难读。
  • 可读性是主观的(我更喜欢这种语法),但最大的优点是您可以准确地确定哪个语句引发了异常。使用该属性,如果您的设置代码抛出您预期的异常,则测试通过。使用此语法,测试将失败。
【解决方案2】:

不确定这是否最近发生了变化,但在 NUnit 3.4.0 中它提供了Assert.Throws&lt;T&gt;

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

【讨论】:

    【解决方案3】:

    如果您仍想使用属性,请考虑:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 2021-11-24
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多