我阅读了 introduction to platform-specific plugins/channels在 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,
);
}
在小部件测试或集成测试中,我如何模拟或 stub channel ,这样我就不必依赖真实设备(运行 Android 或 iOS),例如实际启动 URL?
最佳答案
MethodChannel#setMockMethodCallHandler
现已弃用并删除。
看起来这是现在要走的路:
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void mockUrlLauncher() {
const channel = MethodChannel('plugins.flutter.io/url_launcher');
handler(MethodCall methodCall) async {
if (methodCall.method == 'yourMethod') {
return 42;
}
return null;
}
TestWidgetsFlutterBinding.ensureInitialized();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, handler);
}
详情见GitHub .
以下是 package_info
插件的测试示例,供以后引用:
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void mockPackageInfo() {
const channel = MethodChannel('plugins.flutter.io/package_info');
handler(MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return <String, dynamic>{
'appName': 'myapp',
'packageName': 'com.mycompany.myapp',
'version': '0.0.1',
'buildNumber': '1'
};
}
return null;
}
TestWidgetsFlutterBinding.ensureInitialized();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, handler);
}
关于android - 如何模拟/ stub Flutter 平台 channel /插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43897734/
相关文章:
firebase - 我应该将图片上传到 Cloud Firestore 还是 Firebase S
dart - 如何在 Dart 中将 Class 对象转换为数据结构 `Map` 或 `List o
android - Flutter:使用 Sliver 小部件时如何在滚动时隐藏 BottomApp
flutter - 如何从字节数据中读取蓝牙特征并将其转换为适当的值(用于 flutter 的蓝牙)
flutter - 在 SafeArea 中获取小部件高度的正确方法
generics - 如何从 Dart/Flutter 中的泛型函数调用命名构造函数
dart - 如何在 Dart 中通过 async* 传输错误?