1 | // Copyright 2014 The Flutter Authors. All rights reserved. |
2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. |
4 | |
5 | @TestOn('chrome' ) // Uses web-only Flutter SDK |
6 | library; |
7 | |
8 | import 'dart:ui_web' as ui_web; |
9 | |
10 | import 'package:flutter/services.dart' ; |
11 | import 'package:flutter_test/flutter_test.dart' ; |
12 | import 'package:flutter_web_plugins/flutter_web_plugins.dart' ; |
13 | |
14 | class TestPlugin { |
15 | static void registerWith(Registrar registrar) { |
16 | final MethodChannel channel = MethodChannel( |
17 | 'test_plugin' , |
18 | const StandardMethodCodec(), |
19 | registrar.messenger, |
20 | ); |
21 | final TestPlugin testPlugin = TestPlugin(); |
22 | channel.setMethodCallHandler(testPlugin.handleMethodCall); |
23 | } |
24 | |
25 | static final List<String> calledMethods = <String>[]; |
26 | |
27 | Future<void> handleMethodCall(MethodCall call) async { |
28 | calledMethods.add(call.method); |
29 | } |
30 | } |
31 | |
32 | void main() { |
33 | // Disabling tester emulation because this test relies on real message channel communication. |
34 | ui_web.debugEmulateFlutterTesterEnvironment = false; |
35 | |
36 | group('Plugin Registry' , () { |
37 | setUp(() { |
38 | TestWidgetsFlutterBinding.ensureInitialized(); |
39 | webPluginRegistry.registerMessageHandler(); |
40 | final Registrar registrar = webPluginRegistry.registrarFor(TestPlugin); |
41 | TestPlugin.registerWith(registrar); |
42 | }); |
43 | |
44 | test('can register a plugin' , () { |
45 | TestPlugin.calledMethods.clear(); |
46 | |
47 | const MethodChannel frameworkChannel = |
48 | MethodChannel('test_plugin' ); |
49 | frameworkChannel.invokeMethod<void>('test1' ); |
50 | |
51 | expect(TestPlugin.calledMethods, equals(<String>['test1' ])); |
52 | }); |
53 | |
54 | test('can send a message from the plugin to the framework' , () async { |
55 | const StandardMessageCodec codec = StandardMessageCodec(); |
56 | |
57 | final List<String> loggedMessages = <String>[]; |
58 | ServicesBinding.instance.defaultBinaryMessenger |
59 | .setMessageHandler('test_send' , (ByteData? data) { |
60 | loggedMessages.add(codec.decodeMessage(data)! as String); |
61 | return Future<ByteData?>.value(); |
62 | }); |
63 | |
64 | await pluginBinaryMessenger.send( |
65 | 'test_send' , codec.encodeMessage('hello' )); |
66 | expect(loggedMessages, equals(<String>['hello' ])); |
67 | |
68 | await pluginBinaryMessenger.send( |
69 | 'test_send' , codec.encodeMessage('world' )); |
70 | expect(loggedMessages, equals(<String>['hello' , 'world' ])); |
71 | |
72 | ServicesBinding.instance.defaultBinaryMessenger |
73 | .setMessageHandler('test_send' , null); |
74 | }); |
75 | }); |
76 | } |
77 | |