如何在 Dart 中对 Stream.listen() 进行单元测试

How to unit test Stream.listen() in Dart

考虑以下测试代码...

main() {
  StreamController controller;
  setUp(() {
    controller = StreamController.broadcast(sync: false);
  });

  tearDown(() {
    controller.close();
  });

  test('Stream listen test', () {
    var stream = controller.stream;

    stream.listen((event) {
      // >>>>> How can I test if this was called?? <<<<<<
    });

    controller.add('Here is an event!');
  });
}

...测试调用 stream.listen(...) 回调的正确方法是什么?

stream.listen(...) 不 return 和 Future 所以传统的 expectAsyncX 样式匹配器在这里不起作用。

也许有一些方法可以使用 stream.listen(...) 编辑的 StreamSubscription.asFuture()

你可以使用 expectLater function to wait for async response from your Stream and compare your Stream to your emitted value using emits ,像这样:

  test('Stream listen test', () {
    var stream = controller.stream;

    final String value = 'Here is an event!';

    stream.listen((event) {
      // >>>>> How can I test if this was called?? <<<<<<
    });

    expectLater(stream, emits(value));

    controller.add(value);
  });

更新

您可以围绕 listen 方法尝试 expectAsync1。如果没有发出任何值,将触发超时。

stream.listen(
      expectAsync1(
        (event) {
          expect(event, value);
        },
      ),
    );