NUnit 测试用例预期消息

NUnit TestCase Expected Messages

所以我希望能够在 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

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

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

将您的代码移至 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));
}