5

对于像 2 或 4 这样的每个期望返回值,我想将此值作为单元测试方法的参数传递。但我得到一个例外,即参数不正确。当我删除 countExpected 参数时,单元测试运行良好,我无法断言 countExpected ...

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...
    }
}
4

1 回答 1

8

请参阅此处的说明:

.Returns
从方法返回的预期结果,它必须具有兼容的返回类型。

因此,如果要使用TestCaseData.Returns(),则需要编写 test 如下:

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

    // ACT

    // ASSERT
    return periods.Count();
}

更新:
如果要将期望值作为参数传递,则需要将其作为常规测试用例数据传递。参见示例:

[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...
    }
}
于 2013-03-20T20:52:57.983 回答