小编典典

如何模拟/存根Flutter平台频道/插件?

flutter

我在Flutter网站上阅读了特定于平台的插件/渠道介绍,并浏览了一些简单的插件示例,例如url_launcher

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:flutter/services.dart';

const _channel = const MethodChannel('plugins.flutter.io/url_launcher');

/// Parses the specified URL string and delegates handling of it to the
/// underlying platform.
///
/// The returned future completes with a [PlatformException] on invalid URLs and
/// schemes which cannot be handled, that is when [canLaunch] would complete
/// with false.
Future<Null> launch(String urlString) {
  return _channel.invokeMethod(
    'launch',
    urlString,
  );
}

在窗口小部件测试或集成测试中,如何模拟或存根通道,这样我不必依靠实际设备(运行Android或iOS)说实际上启动URL?


阅读 302

收藏
2020-08-13

共1个答案

小编典典

您可以使用setMockMethodCallHandler为基础方法通道注册模拟处理程序:

https://docs.flutter.io/flutter/services/MethodChannel/setMockMethodCallHandler.html

final List<MethodCall> log = <MethodCall>[];

MethodChannel channel = const MethodChannel('plugins.flutter.io/url_launcher');

// Register the mock handler.
channel.setMockMethodCallHandler((MethodCall methodCall) async {
  log.add(methodCall);
});

await launch("http://example.com/");

expect(log, equals(<MethodCall>[new MethodCall('launch', "http://example.com/")]));

// Unregister the mock handler.
channel.setMockMethodCallHandler(null);
2020-08-13