首页 > 解决方案 > Flutter/Dart 在单元测试中等待几秒钟

问题描述

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

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

});

标签: unit-testingdartflutterwait

解决方案


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

});

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


推荐阅读