MqttTransportHandler CreateTransportHandlerWithMockChannel(out IChannel channel, Action <object, ConnectionEventArgs> onConnectionOpenedCallback, Func <object, ConnectionEventArgs, Task> onConnectionClosedCallback) { var _channel = Substitute.For <IChannel>(); channel = _channel; MqttTransportHandler transport = null; // The channel factory creates the channel. This gets called from inside OpenAsync. // Unfortunately, it needs access to the internals of the transport (like being able to call OnConnceted, which is passed into the Mqtt channel constructor, but we're not using that) Func <IPAddress, int, Task <IChannel> > factory = (a, i) => { transport.OnConnected(); return(Task <IChannel> .FromResult <IChannel>(_channel)); }; transport = new MqttTransportHandler(new PipelineContext(), IotHubConnectionStringExtensions.Parse(DumpyConnectionString), new MqttTransportSettings(Microsoft.Azure.Devices.Client.TransportType.Mqtt_Tcp_Only), factory, onConnectionOpenedCallback, onConnectionClosedCallback); return(transport); }