首页 > 解决方案 > 在 Flutter 中运行单元测试时出现 MissingPluginException

问题描述

我正在使用Google ML Kit Plugin从给定的图像中扫描条形码和二维码,我尝试为 Google ML Kit Plugin 提供的 processImage 方法编写单元测试。在运行我的测试代码时,我遇到了这个错误。我附上了我的单元测试代码和应用程​​序代码。

错误:

C:\FlutterSDK\Flutter2.5.2\flutter\bin\flutter.bat --no-color test --machine --start- 
paused test\view\widgets\barcodescanner_test.dart
Testing started at 11:20 ...

package:flutter/src/services/platform_channel.dart 154:7  MethodChannel._invokeMethod

MissingPluginException(No implementation found for method vision#startBarcodeScanner on 
channel google_ml_kit)

测试代码:

test('barcode test',() async {
BarcodeScannerUtil barcodeScannerUtil=BarcodeScannerUtil();
List<Barcode> barcodeList=await barcodeScannerUtil.getBarcode(InputImage.fromFilePath(r'C:\FlutterProjects\KK\Project\Dev\assets\images\ac.png'));
expect(barcodeList.length, 0);
});

我的代码:

class BarcodeScannerUtil {
  BarcodeScanner barcodeScanner = GoogleMlKit.vision.barcodeScanner();

  Future<List<Barcode>> getBarcode(InputImage inputImage) async {
    List<Barcode> barcodeList = await barcodeScanner.processImage(inputImage);
    return barcodeList;
  }

  void close() {
    barcodeScanner.close();
  }
}

标签: flutterunit-testingdartbarcode-scannergoogle-mlkit

解决方案


test('Barcode Method Test',() async {
  const MethodChannel('google_ml_kit')
      .setMockMethodCallHandler((MethodCall methodCall) async {
    if (methodCall.method == 'vision#startBarcodeScanner') {
      return <Barcode>[];
    }
    return null;
  });
  BarcodeScannerUtil barcodeScannerUtil=BarcodeScannerUtil();
  List<Barcode> barcodeList=await barcodeScannerUtil.getBarcode(InputImage.fromFilePath(r'C:\FlutterProjects\KK\Project\Dev\assets\images\ac.png'));
  expect(barcodeList.length, 0);
});

推荐阅读