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

Rag*_*gas 8 unit-testing wait dart flutter

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

// 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);

});
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 12

您可以使用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);

});
Run Code Online (Sandbox Code Playgroud)

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

  • 您在某处缺少“async”。请使用您当前的代码更新您的问题。 (2认同)