如何测试原生调用Flutter的方法通道?

How to test method channel that call from native to Flutter?

我正在开发本机插件并尝试进行单元测试。 所有单元测试都将在 Dart 中完成(无本机代码)。

Flutter 有一个测试示例,说明如何使用 setMockMethodCallHandler 测试从 Dart 到本机的调用方法通道。

问题是我还没有找到测试方法通道的方法,该通道从本机调用到使用 setMethodCallHandler 处理来自本机的调用的 Dart。

这是一个例子

// main.dart

class Plugin {

  static MethodChannel _channel = const MethodChannel('plugin');
 
  Plugin() {
    _channel.setMethodCallHandler((call) async {
      print("called from native: ${call.method}");
    });
  }

}
// tests/main_test.dart

void main() {
  const MethodChannel _channel = MethodChannel('core.super_router');
  Plugin plugin;

  setUp(() async {
    TestWidgetsFlutterBinding.ensureInitialized();
    plugin = Plugin();
  });

  test("call from native", () async {
    _channel.invokeMethod("something");
    // This call can't reach the handler in the Plugin
    // And there is no method like mockInvokeMethod
  });
}

下面的代码段基于 CyrilHu 的 方法非常适合我。

test("Listening device", () async {

    ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
    'channnelName',
    StandardMethodCodec().encodeMethodCall(
        MethodCall('methodName', '{"result":true}')),(ByteData data){});

     ...
});