Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup a complicated row test with nunit and TestCaseSource and TestCaseData

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...
    }
}
like image 396
Elisabeth Avatar asked Mar 20 '13 20:03

Elisabeth


1 Answers

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...
    }
}
like image 178
Alexander Stepaniuk Avatar answered Oct 01 '22 22:10

Alexander Stepaniuk