我想运行一个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中进行设置.

您还可以创建一个helper函数,然后完全删除 map (这是我通常做的事情):

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都会引入一个具有自己名称的新测试,并且每个测试都可能单独失败.

Dart相关问答推荐

Dart StreamController().stream 等于 == 但不相同

?? ("if null") 运算符类型解析问题

angular.dart NgTwoWay 和 NgAttr 已弃用?

浮动操作按钮:如何像 RaisedButton 一样更改启动 colored颜色 和突出显示 colored颜色 ?

Flutter/Dart 为 Google Maps Marker 添加自定义点击事件

如何等待forEach完成异步回调?

不要将 PageView 居中 - Flutter

判断无状态小部件是否在Flatter中处理

Dart:Streams与 ValueNotifiers

Firebase Crashlytics 崩溃未报告给 Flutter 中的 Firebase 控制台

Flutter 中 ChangeNotifier 的构建器小部件

Flutter 如何使用 ListTile 三行

如何在 Visual Studio Code 中禁用fake右括号注释?

如何在 Dart 中使用 char 类型?

可选参数的默认值必须是常量

Dart,对泛型的限制?

函数调用前的感叹号是什么意思?

我应该如何在 Dart 中测试 Future?

在 Dart 中,bool是否有parse,就像int一样?

如何在 Dart 中运行重复出现的函数?