Dart支持参数化单元测试吗?
我想运行一个Dart测试,该测试使用一组输入和预期输出重复进行,类似于JUnit的测试 我编写了以下测试以实现类似的行为,但问题是,如果所有测试输出计算不正确,测试只会失败一次:Dart支持参数化单元测试吗?,dart,Dart,我想运行一个Dart测试,该测试使用一组输入和预期输出重复进行,类似于JUnit的测试 我编写了以下测试以实现类似的行为,但问题是,如果所有测试输出计算不正确,测试只会失败一次: import 'package:test/test.dart'; void main() { test('formatDay should format dates correctly', () async { var inputsToExpected = { DateTime(2018, 1
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
- Dart的
测试
软件包很聪明,因为它不想太聪明。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
的所有调用都应该同步进行,因此不要在异步函数中调用它。如果在运行测试之前需要时间进行设置,请改为在设置中进行设置
您还可以创建一个helper函数,并完全删除映射(这是我通常做的):
在这里,每次调用checkFormat都会引入一个新的测试,每个测试都有自己的名称,并且每个测试都可能单独失败。新颖的方法顺便说一句。要为单个参数提供更详细的输出,您可以嵌套组
(您无法使用测试
)非常酷。我想测试抽象类(键值存储)的不同实现,但重用相同的测试用例。这个答案帮助很大。
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");
});