如何在 dart 的单元测试中设置测试的超时时间?

Fre*_*ind 7 dart dart-unittest dart-async

是否可以设置测试可以运行的最长时间?就像:

@Test(timeout=1000)
public void testSomething() {}
Run Code Online (Sandbox Code Playgroud)

在 jUnit 中?

atr*_*eon 7

是的,您现在可以将这行代码放在导入语句之上,以确定您的测试超时时间。

@Timeout(const Duration(seconds: 45))
Run Code Online (Sandbox Code Playgroud)

https://pub.dartlang.org/packages/test#timeouts

  • 这个答案是比使用计时器更好的做法。 (2认同)

Gün*_*uer 4

main()尝试在您的测试中添加以下行

void main(List<String> args) {
  useHtmlEnhancedConfiguration(); // (or some other configuration setting)
  unittestConfiguration.timeout = new Duration(seconds: 3); // <<== add this line

  test(() {
    // do some tests
  });
}
Run Code Online (Sandbox Code Playgroud)

setUp()您可以使用和轻松设置时间tearDown()保护Timer

library x;

import 'dart:async';
import 'package:unittest/unittest.dart';

void main(List<String> args) {
  group("some group", () {
    Timer timeout;
    setUp(() {
      // fail the test after Duration
      timeout = new Timer(new Duration(seconds: 1), () => fail("timed out"));
    });

    tearDown(() {
        // if the test already ended, cancel the timeout
        timeout.cancel();
    });

    test("some very slow test", () {
      var callback = expectAsync0((){});
      new Timer(new Duration(milliseconds: 1500), () {
        expect(true, equals(true));
        callback();
      });
    });

    test("another very slow test", () {
      var callback = expectAsync0((){});
      new Timer(new Duration(milliseconds: 1500), () {
        expect(true, equals(true));
        callback();
      });
    });


    test("a fast test", () {
      var callback = expectAsync0((){});
      new Timer(new Duration(milliseconds: 500), () {
        expect(true, equals(true));
        callback();
      });
    });

  });
}
Run Code Online (Sandbox Code Playgroud)

这会使整个组失败,但组可以嵌套,因此您可以完全控制应该监视哪些测试是否超时。