2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.mqtt.handler;
15 import static org.mockito.Mockito.spy;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
23 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
24 import org.openhab.core.io.transport.mqtt.internal.Subscription;
25 import org.openhab.core.io.transport.mqtt.internal.client.MqttAsyncClientWrapper;
28 * We need an extended MqttBrokerConnection to overwrite the protected `connectionCallbacks` with
29 * an instance that takes the mocked version of `MqttBrokerConnection` and overwrite the connection state.
31 * We also replace the internal MqttAsyncClient with a spied one, that in respect to the success flags
32 * immediately succeed or fail with publish, subscribe, unsubscribe, connect, disconnect.
34 * @author David Graeff - Initial contribution
37 public class MqttBrokerConnectionEx extends MqttBrokerConnection {
38 public MqttConnectionState connectionStateOverwrite = MqttConnectionState.DISCONNECTED;
39 public boolean publishSuccess = true;
40 public boolean subscribeSuccess = true;
41 public boolean unsubscribeSuccess = true;
42 public boolean disconnectSuccess = true;
43 public boolean connectSuccess = true;
44 public boolean connectTimeout = false;
46 public MqttBrokerConnectionEx(String host, @Nullable Integer port, boolean secure, String clientId) {
47 super(host, port, secure, clientId);
50 public void setConnectionCallback(MqttBrokerConnectionEx o) {
51 connectionCallback = spy(new ConnectionCallback(o));
54 public Map<String, Subscription> getSubscribers() {
58 public ConnectionCallback getCallback() {
59 return connectionCallback;
63 protected MqttAsyncClientWrapper createClient() {
64 return new MqttAsyncClientWrapperEx(this);
68 public @NonNull MqttConnectionState connectionState() {
69 return connectionStateOverwrite;