Setup a complicated row test with nunit and TestCaseSource and TestCaseData

Elisabeth picture Elisabeth · Mar 20, 2013 · Viewed 8.4k times · Source

For every expect return value like 2 or 4 I want to pass this value as parameter for the unit test method. But I get an exception that the parameters are not correct. When I remove the countExpected parameter the unit test runs fine I just can not assert the countExpected...

Is this scenario possible at all with NUnit?

[Test, TestCaseSource("VisibleWeekDays")]
public void Test(DayOfWeek[] visibleWeekDaysSetup, int countExpected)
{
    // ARRANGE

    // ACT

    // ASSERT
    Assert.That(periods.Count(),Is.EqualTo(countExpected));
}

private static IEnumerable<TestCaseData> VisibleWeekDays
{
    get
    {
        yield return new TestCaseData(new DayOfWeek[] {DayOfWeek.Sunday}).Returns(2);
        yield return new TestCaseData(new DayOfWeek[] {DayOfWeek.Sunday, DayOfWeek.Monday}).Returns(4);
        // more days...
    }
}

Answer

Alexander Stepaniuk picture Alexander Stepaniuk · Mar 20, 2013

See explanation here:

.Returns
The expected result to be returned from the method, which must have a compatible return type.

So, if you want to use TestCaseData.Returns(), you need to write test as the following:

[Test, TestCaseSource("VisibleWeekDays")]
public int Test(DayOfWeek[] visibleWeekDaysSetup)
{
     // ARRANGE

    // ACT

    // ASSERT
    return periods.Count();
}

UPDATE:
If you want to pass expected value as a parameter, you need to pass it as regular test case data. See example:

[Test, TestCaseSource("VisibleWeekDays")]
public void Test(DayOfWeek[] visibleWeekDaysSetup, int countExpected)
{
    ...

    Assert.That(periods.Count(),Is.EqualTo(countExpected));
}

private static IEnumerable<TestCaseData> VisibleWeekDays
{
    get
    {
        yield return new TestCaseData(new DayOfWeek[] {DayOfWeek.Sunday}, 2);
        yield return new TestCaseData(new DayOfWeek[] {DayOfWeek.Sunday, DayOfWeek.Monday}, 4);
        // more days...
    }
}