是的,您可以在单元测试中使用循环,但要小心。正如 Alex York 所提到的,如果你测试 one 东西,循环是可以接受的;即一个期望。
如果你使用循环,那么我建议你必须做两件事:
- 如上所述,测试非空迭代集。遍历空集是误报。假阳性结果是所有自动化测试的祸根,因为没有人会仔细检查绿色结果。
- 包括描述当前迭代的测试描述。至少包括迭代索引。
这是我测试对象的大于属性的示例。
[Test]
public void TestCompare_XtoY_GreaterThan()
{
int numObjects = mOrderedList.Count;
for (int i = 1; i < numObjects; ++i)
{
for (int j = 0; j < i; ++j)
{
string testDescription = string.Format("{0} is greater than {1} which implies\n {2}\n is greater than\n {3}"
, i, j
, mOrderedList[i], mOrderedList[j]
);
Assert.IsTrue(0 < mOrderedList[i].CompareTo(mOrderedList[j]), testDescription);
Assert.IsTrue(0 < mOrderedList[i].Compare(mOrderedList[i], mOrderedList[j]), testDescription);
Assert.IsTrue(0 < mOrderedList[j].Compare(mOrderedList[i], mOrderedList[j]), testDescription);
Assert.Greater(mOrderedList[i], mOrderedList[j], testDescription);
}
}
}
我在测试设置中测试我的有序列表是非空的:
[SetUp]
public void GeneralTestSetup()
{
// verify the iterated sources are not empty
string testDescription = string.Format("The ordered list of objects must have at least 3 elements, but instead has only {0}.", mOrderedList.Count);
Assert.IsTrue(2 < mOrderedList.Count, testDescription);
}
即使在我的循环中,我也有多个断言,但所有断言都在测试单一期望:
if i > j then mOrderedList[i] > mOrderedList[j]
迭代级别的测试描述是这样的,你会得到失败,例如:
10 is greater than 9 which implies
TestActionMethodInfo: [Actions.File, Version=1.0.446.0, File, VerifyReadOnly]
is greater than
TestActionMethodInfo: [Actions.File, Version=1.0.446.0, File, Write]
Expected: True
But was: False
而不仅仅是:
Expected: True
But was: False
上面关于我的代码的问题/辩论:
我是在测试一件事吗?
我断言对象内有 4 种不同的比较方法,可以说是测试 4 件事而不是一个。计数器大于等于大于,并且进行该评估的所有方法都应该是一致的。