首页 > 解决方案 > 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));
    });
  });
}

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

标签: dart

解决方案


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


推荐阅读