Dart's test
包很聪明,因为它并不想变得太聪明。这test
function 只是您调用的函数,您可以在任何地方调用它,甚至在循环或另一个函数调用内。
因此,对于您的示例,您可以执行以下操作:
group("formatDay should format dates correctly:", () {
var inputsToExpected = {
DateTime(2018, 11, 01): "Thu 1",
...
DateTime(2018, 11, 07): "Wed 7",
DateTime(2018, 11, 30): "Fri 30",
};
inputsToExpected.forEach((input, expected) {
test("$input -> $expected", () {
expect(formatDay(input), expected);
});
});
});
唯一要记住的重要事情是所有的调用test
应该同步发生时main
函数被调用,因此不在异步函数内调用它。如果您在运行测试之前需要时间进行设置,请在setUp
反而。
您还可以创建一个辅助函数,然后完全删除地图(这是我通常所做的):
group("formatDay should format dates correctly:", () {
void checkFormat(DateTime input, String expected) {
test("$input -> $expected", () {
expect(formatDay(input), expected);
});
}
checkFormat(DateTime(2018, 11, 01), "Thu 1");
...
checkFormat(DateTime(2018, 11, 07), "Wed 7");
checkFormat(DateTime(2018, 11, 30), "Fri 30");
});
这里,每次调用 checkFormat 都会引入一个具有自己名称的新测试,并且每个测试都可能单独失败。