Flutter/Dart 在单元测试中等待几秒钟

Flutter/Dart wait for a few seconds in unit testing

我正在写一个计时器应用程序。在单元测试中,如何等待几秒钟来测试我的计时器是否正常工作?

// I want something like this.
test("Testing timer", () {
    int startTime = timer.seconds;
    timer.start();

    // do something to wait for 2 seconds

    expect(timer.seconds, startTime - 2);

});

您可以使用 awaitFuture.delayed(...)`:

test("Testing timer", () async {
    int startTime = timer.seconds;
    timer.start();

    // do something to wait for 2 seconds
    await Future.delayed(const Duration(seconds: 2), (){});

    expect(timer.seconds, startTime - 2);

});

另一种方法是 fake_async 和 https://pub.dartlang.org/packages/clock,以便能够自由操纵测试中使用的时间。

为此,您可以使用 fake_async 包。允许在 flutter 中伪造异步事件,例如用于确定性测试的定时器和微任务

此包提供了 FakeAsync class,这使得确定性地测试使用异步功能(如 Futures 的代码变得容易StreamsTimersmicrotasks。它创建了一个环境,用户可以在其中明确控制 Dart 的“当前时间”概念。当时间提前时,FakeAsync 会触发为该时间段安排的所有异步事件,而实际上不需要测试等待实时结束。

例如:

import 'dart:async';

import 'package:fake_async/fake_async.dart';
import 'package:test/test.dart';

void main() {
  test("Future.timeout() throws an error once the timeout is up", () {
    // Any code run within [fakeAsync] is run within the context of the
    // [FakeAsync] object passed to the callback.
    fakeAsync((async) {
      // All asynchronous features that rely on timing are automatically
      // controlled by [fakeAsync].
      expect(new Completer().future.timeout(new Duration(seconds: 5)),
          throwsA(new isInstanceOf<TimeoutException>()));

      // This will cause the timeout above to fire immediately, without waiting
      // 5 seconds of real time.
      async.elapse(new Duration(seconds: 5));
    });
  });
}