如何测试流在单元测试(Flutter)的时间间隔内发出任何东西?

Val*_*ova 6 unit-testing flutter

在我的代码中,该函数在一分钟后向流发出值。假设它是一个计时器。我想做单元测试(不是小部件测试,因为该函数存在于 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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我的测试代码:

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));
  });
}
Run Code Online (Sandbox Code Playgroud)

小智 0

我也遇到了同样的问题。它似乎不太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 */);
  });
}
Run Code Online (Sandbox Code Playgroud)