service_mocker.dart 1.29 KB
Newer Older
1 2 3 4
// Copyright 2015 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.

5
import 'package:flutter/services.dart';
6
import 'package:mojo/bindings.dart' as bindings;
7 8 9

// Tests can use ServiceMocker to register replacement implementations
// of Mojo services.
10 11
class ServiceMocker {
  ServiceMocker._() {
12
    shell.overrideConnectToService = _connectToService;
13 14 15
  }

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

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

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

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