Dart 支持参数化单元测试吗?

2024-01-01

我想运行一个 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));
    });
  });
}

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

  • 只写一个测试
  • Test n不同的输入/输出
  • Fail n次如果全部n测试被破坏

Dart's test包很聪明,因为它并不想变得太聪明。这testfunction 只是您调用的函数,您可以在任何地方调用它,甚至在循环或另一个函数调用内。 因此,对于您的示例,您可以执行以下操作:

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Dart 支持参数化单元测试吗? 的相关文章

随机推荐