[英]In Dart, how to verify a void method that does not throw exception in unit tests?
[英]Does Dart support parameterized unit tests?
我想运行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);
});
});
});
需要记住的唯一重要的事情是,所有的呼叫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的每次调用都会引入一个具有自己名称的新测试,并且每个测试都会单独失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.