setMockMessageHandler method
- String channel,
- MessageHandler? handler, [
- 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 await
ing 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:
-
checkMockMessageHandler, which can verify if a handler is still registered, which is useful in tests to ensure that no unexpected handlers are being registered.
-
setMockDecodedMessageHandler, which wraps this method but decodes the messages using a MessageCodec.
-
setMockMethodCallHandler, which wraps this method but decodes the messages using a MethodCodec.
-
setMockStreamHandler, which wraps setMockMethodCallHandler to handle EventChannel messages.
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;
}
}