dart - 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);
});
});
});
唯一要记住的重要一点是,所有调用都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 都会引入一个具有自己名称的新测试,并且每个测试都可能单独失败。
推荐阅读
- optaplanner - 将自动连线 SolverManager 与 Optaplanner 一起使用时,如何访问 scoreDirector?
- django - 在 django 中使用 pytest 和 mock 获取状态码
- c# - 如何在 asp.net 核心中获得博客帖子看到访问者?
- postgresql - Postgres 何时以及如何使用“transactionid”锁
- sql - 更新上个月喜欢的商品
- javascript - 在 php MVC 上使用 ajax 请求
- webpack - npm run dev 不会自动刷新最新更改
- sql - 为批量导入创建格式文件
- python - 后端文件夹中的 urls.py 文件 - 需要在前端文件夹中找到 index.html
- r - 如何检索每个客户的集群号属于 R 中的质心