NUnit TestCase预期消息

Joe*_*ber 2 c# nunit unit-testing exception testcase

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

这是原作

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

public void AddHolidays_StartsInvlaid()
{}
Run Code Online (Sandbox Code Playgroud)

这是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)
{}
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*use 6

如果可以,我建议远离ExpectedException.这被认为是一种不好的做法,因为如果你的测试中的代码抛出了你不期望它的相同异常,它会导致误报.因此,ExpectedException已从NUnit 3中删除.另外,正如您所发现的那样,ExpectedExceptionNUnit中的所有数据驱动属性也不完全受支持.

移动代码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));
}
Run Code Online (Sandbox Code Playgroud)