对于每个期望返回值,如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...
}
}
答案 0 :(得分:6)
见解释here:
<强> .Returns 强>
从该方法返回的预期结果,该方法必须具有兼容的返回类型。
因此,如果您想使用TestCaseData.Returns()
,则需要按以下方式编写测试:
[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...
}
}