Search code examples
c#unit-testingexceptionnunittestcase

NUnit TestCase Expected Messages


So I want to be able to specify different Exception messages in the TestCase but have no idea how that is done

This is the original

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

public void AddHolidays_StartsInvlaid()
{}

This is it with 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)
{}

The method works fine but I just want to be able to specify the exception message with NUnit TestCase


Solution

  • If you can, I would recommend moving away from ExpectedException. It is considered a bad practice because it can lead to false positives if code in your tests throws the same exception where you weren't expecting it. Because of this, ExpectedException has been removed from NUnit 3. Also, as you have found, ExpectedException is also not fully supported across all of the data driven attributes in NUnit.

    Moving your code to Assert.Throws will solve your problem. You can pass in the expected message from the TestCase as a regular parameter. I will simplify for readability;

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