NUnit TestCase 预期消息

3

我希望能够在TestCase中指定不同的异常消息,但我不知道如何实现。

这是原始文本。

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

public void AddHolidays_StartsInvlaid()
{}

这是与测试用例相关的IT技术内容。
[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中指定异常消息。

2个回答

7
如果可以的话,我建议你不要再使用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));
}

1
我认为你的Assert::Throws重载带有消息,它需要断言失败显示消息而不是期望消息:/// <param name="message">The message that will be displayed on failure</param>-因此,如果抛出异常,则会以任何消息通过。 - hypersw

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接