Dart支持参数化单元测试吗



我想运行一个Dart测试,它用一组输入和预期输出重复,类似于JUnit。

我写了下面的测试来实现类似的行为,但问题是,如果所有测试输出都计算错误,测试只会失败一次:

import 'package:test/test.dart';
void main() {
test('formatDay should format dates correctly', () async {
var inputsToExpected = {
DateTime(2018, 11, 01): "Thu 1",
...
DateTime(2018, 11, 07): "Wed 7",
DateTime(2018, 11, 30): "Fri 30",
};
// When
var inputsToResults = inputsToExpected.map((input, expected) =>
MapEntry(input, formatDay(input))
);
// Then
inputsToExpected.forEach((input, expected) {
expect(inputsToResults[input], equals(expected));
});
});
}

我想使用参数化测试的原因是,这样我就可以在测试中实现以下行为:

  • 只写一个测试
  • 测试n不同的输入/输出
  • 如果所有n测试都失败,则n次失败

Dart的test包很聪明,因为它不想太聪明。test函数只是您调用的一个函数,您可以在任何地方调用它,甚至可以在循环或其他函数调用中调用它。因此,对于您的示例,您可以执行以下操作:

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);
});
});
});

唯一需要记住的是,当调用main函数时,对test的所有调用都应该同步进行,因此不要在异步函数内调用它。如果在运行测试之前需要时间进行设置,请在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的每个调用都会引入一个具有自己名称的新测试,并且每个调用都可能单独失败。

最新更新