service_mocker.dart 1.13 KB
Newer Older
1
import 'package:flutter/services.dart';
2
import 'package:mojo/bindings.dart' as bindings;
3 4 5

// Tests can use ServiceMocker to register replacement implementations
// of Mojo services.
6 7
class ServiceMocker {
  ServiceMocker._() {
8
    shell.overrideConnectToService = _connectToService;
9 10 11
  }

  // Map of interface names to mock implementations.
12
  Map<String, Object> _interfaceMocks = <String, Object>{};
13

14
  bool _connectToService(String url, bindings.ProxyBase proxy) {
15
    Object mock = _interfaceMocks[proxy.serviceName];
16 17
    if (mock != null) {
      // Replace the proxy's implementation of the service interface with the
18 19
      // mock. The mojom bindings put the "ptr" field on all proxies.
      (proxy as dynamic).ptr = mock;
20 21 22 23 24 25 26
      return true;
    } else {
      return false;
    }
  }

  // Provide a mock implementation for a Mojo interface.
27 28
  // Make sure you initialise the binding before calling this.
  // For example, by calling `WidgetFlutterBinding.ensureInitialized();`
29
  void registerMockService(String interfaceName, Object mock) {
30
    _interfaceMocks[interfaceName] = mock;
31 32 33
  }
}

34
final ServiceMocker serviceMocker = new ServiceMocker._();