【问题标题】:NUnit TestCase Expected MessagesNUnit 测试用例预期消息
【发布时间】:2016-08-30 21:54:26
【问题描述】:

所以我希望能够在 TestCase 中指定不同的异常消息,但不知道如何完成

这是原版

[Test]
[ExpectedException(typeof(SystemException), ExpectedMessage = "Holiday cannot start or end on a weekend or non-working day")]

public void AddHolidays_StartsInvlaid()
{}

TestCase 就是这样

[TestCase("27/04/2025", "28/05/2025", "FullDay", "FullDay", ExpectedMessage = "Holiday cannot start or end on a weekend or non-working day")]
[ExpectedException(typeof(SystemException), ExpectedMessage)]

public void AddHolidays_Exceptions(string dateFrom, string dateTo, string fromPeriod, string toPeriod)
{}

该方法工作正常,但我只想能够使用 NUnit TestCase 指定异常消息

【问题讨论】:

    标签: c# unit-testing exception nunit testcase


    【解决方案1】:

    假设您继续使用 NUnit 2.x,只需使用 TestCaseAttribute 的 ExpectedException 属性。

    【讨论】:

      【解决方案2】:

      如果可以,我建议您离开ExpectedException。这被认为是一种不好的做法,因为如果测试中的代码在您没有预料到的地方抛出相同的异常,它可能会导致误报。因此,ExpectedException 已从 NUnit 3 中删除。此外,正如您所发现的,NUnit 中的所有数据驱动属性也并不完全支持 ExpectedException

      将您的代码移至Assert.Throws 将解决您的问题。您可以将来自TestCase 的预期消息作为常规参数传递。为了便于阅读,我将简化;

      [TestCase("27/04/2025", "Holiday cannot start or end on a weekend or non-working day")]
      public void AddHolidays_Exceptions(string date, string expectedMessage)
      {
          Assert.That(() => ParseDate(date), Throws.ArgumentException.With.Message.EqualTo(expectedMessage));
      }
      

      【讨论】:

      • 我认为您的 Assert::Throws 重载消息会显示断言失败显示消息而不是预期消息:/// <param name="message">The message that will be displayed on failure</param> — 因此,如果完全抛出异常,它将与任何消息一起通过
      猜你喜欢
      • 2011-07-31
      • 2013-10-08
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      相关资源
      最近更新 更多