setMockMessageHandler method

void setMockMessageHandler(
  1. String channel,
  2. MessageHandler? handler, [
  3. Object? identity
])

Set a callback for intercepting messages sent to the platform on the given channel, without decoding them.

Intercepted messages are not forwarded to the platform.

The given callback will replace the currently registered callback for that channel, if any. To stop intercepting messages at all, pass null as the handler.

The handler's return value, if non-null, is used as a response, unencoded.

It is strongly recommended that all handlers used with this API be synchronous (not requiring any microtasks to complete), because testWidgets tests run in a FakeAsync zone in which microtasks do not progress except when time is explicitly advanced (e.g. with WidgetTester.pump), which means that awaiting a Future will result in the test hanging.

The identity argument, if non-null, is used to identify the callback when checked by checkMockMessageHandler. If null, the handler is used instead. (This allows closures to be passed as the handler with an alias used as the identity so that a reference to the closure need not be used. In practice, this is used by setMockDecodedMessageHandler and setMockMethodCallHandler to allow checkMockMessageHandler to recognize the closures that were passed to those methods even though those methods wrap those closures when passing them to this method.)

Registered callbacks are cleared after each test.

See also:

Implementation

void setMockMessageHandler(String channel, MessageHandler? handler, [ Object? identity ]) {
  if (handler == null) {
    _outboundHandlers.remove(channel);
    _outboundHandlerIdentities.remove(channel);
  } else {
    identity ??= handler;
    _outboundHandlers[channel] = handler;
    _outboundHandlerIdentities[channel] = identity;
  }
}