【问题标题】:How to test that stream emits anything during time interval in unit tests (Flutter)?如何在单元测试(颤振)的时间间隔内测试该流发出任何东西?
【发布时间】:2019-10-15 18:59:28
【问题描述】:

在我的代码中,函数在一分钟后向流发出值。假设它是一个计时器。我想做单元测试(不是小部件测试,因为该函数位于 bloc 文件中)。我尝试按照文档https://api.flutter.dev/flutter/quiver.testing.async/FakeAsync-class.html 中的描述使用 fakeAsync,但没有运气。超时测试失败。 测试代码:

class BarcodeBloc {
  Timer _timer;
  StreamController<bool> _timerFinished;

  BarcodeBloc() {
    _timerFinished = new StreamController();
  }

  Stream<bool> get cameraTimeout => _timerFinished.stream;

  void _tick() {
    _timerFinished.add(true);
  }

  void startTimer() {
    stopTimer();
    print("starting timer");
    _timer = Timer(interval, _tick);
  }

  void stopTimer() {
    if (_timer != null) {
      _timer.cancel();
    }
  }
}

我的测试代码:

void main() {

  test("After one minute emits true", () {
    new FakeAsync().run((async) {
       BarcodeBloc barcodeBloc = new BarcodeBloc(preferenceProvider);
       barcodeBloc.startTimer();

       async.elapse(duration);
       expect(barcodeBloc.cameraTimeout, emits(true));
  });
}

【问题讨论】:

  • 不确定你是否仍然有这个问题,但我正在做一些非常类似的事情,使用 async.elapse 在由于使用 debounce() 而有时间延迟的流上快进时间并且在标准单元测试(not 小部件测试)中使用当前的 strable v1.12.13+hotfix.7)按预期工作。

标签: unit-testing flutter


【解决方案1】:

我遇到了同样的问题。 emits 似乎不适用于 FakeAsync 并且我在使用 FakeAsync 区域内的任何 await 调用时遇到问题,所以我最终做的是:

void main() {
  var streamOutput;

  test("After one minute emits true", () {
    FakeAsync().run((async) {
       BarcodeBloc barcodeBloc = BarcodeBloc(preferenceProvider);
       barcodeBloc.startTimer();
       barcodeBloc.cameraTimeout.listen((value) {
         streamOutput = value;
       });

       async.elapse(duration);
       expect(streamOutput, /* expected value */);
  });
}

【讨论】:

    猜你喜欢
    • 2018-12-20
    • 2020-12-04
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 2012-02-20
    相关资源
    最近更新 更多