簡體   English   中英

測試在 Isolate 上運行代碼的 Dart class

[英]Testing Dart class that runs code on Isolate

我有一個在 Isolate 上執行計算的 Dart class。 這是我的代碼:

class Mapper {
  SendPort _isolateSendPort;
  Isolate _isolate;

  Mapper() {
    _asyncInit();
  }

  void _asyncInit() async {
    final receivePort = ReceivePort();
    _isolate = await Isolate.spawn(
      _mappingFunction,
      receivePort.sendPort,
    );
    _isolateSendPort = await receivePort.first;
  }

  static void _mappingFunction(SendPort callerSendPort) {
    final newIsolateReceivePort = ReceivePort();
    callerSendPort.send(newIsolateReceivePort.sendPort);

    newIsolateReceivePort.listen((dynamic message) {
        final crossIsolatesMessage =
          message as CrossIsolatesMessage<Input>;

        // some computations...

        crossIsolatesMessage.sender.send(output);
    });
  }

  Future<Output> map(Input input) async {
    final port = ReceivePort();
    _isolateSendPort.send(CrossIsolatesMessage<Input>(
      sender: port.sendPort,
      message: input,
    ));
    return port.map((event) => event as Output).first;
  }

  void dispose() {
    _isolate?.kill(priority: Isolate.immediate);
    _isolate = null;
  }
}

class CrossIsolatesMessage<T> {
  final SendPort sender;
  final T message;

  CrossIsolatesMessage({
    @required this.sender,
    this.message,
  });
}

當我運行 Flutter 應用程序時,此代碼運行良好。 但是公共方法Future<Output> map(Input input)的單元測試會引發錯誤NoSuchMethodError ,這_isolateSendPort是 null。

下面是單元測試代碼:

test('Mapper map', () {
  final sut = Mapper();
  final inputDummy = Input('123');
  final resultFuture = sut.map(inputDummy);
  final expectedResult = Output('321');
  expectLater(resultFuture, completion(expectedResult));
});

這是一個錯誤:

NoSuchMethodError: The method 'send' was called on null.
Receiver: null
Tried calling: send(Instance of 'CrossIsolatesMessage<Input>')
dart:core                                                  Object.noSuchMethod

為什么在測試中會出現這個錯誤? 為這個 class 編寫測試的正確方法是什么?

問題解決了。

_isolate_isolateSendPort的創建是異步操作。 這就是為什么_isolateSendPort在測試中是 null 的原因。 Mapper構造函數調用方法_asyncInit()是創建隔離的錯誤方法。

這是具有延遲隔離初始化的工作解決方案:

class Mapper {
  SendPort _isolateSendPort;
  Isolate _isolate;

  void _initIsolate() async {
    final receivePort = ReceivePort();
    _isolate = await Isolate.spawn(
      _mappingFunction,
      receivePort.sendPort,
    );
    _isolateSendPort = await receivePort.first;
  }

  ...

  Future<Output> map(Input input) async {
    final port = ReceivePort();
    if (_isolateSendPort == null) {
      await _initIsolate();
    }
    _isolateSendPort.send(CrossIsolatesMessage<Input>(
      sender: port.sendPort,
      message: input,
    ));
    return port.map((event) => event as Output).first;
  }

  ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM