diff --git a/homeassistant/components/mqtt/client.py b/homeassistant/components/mqtt/client.py index 02f3edd155a..2e4d49b4cd9 100644 --- a/homeassistant/components/mqtt/client.py +++ b/homeassistant/components/mqtt/client.py @@ -176,7 +176,13 @@ async def async_subscribe( raise HomeAssistantError( f"Cannot subscribe to topic '{topic}', MQTT is not enabled" ) - mqtt_data = get_mqtt_data(hass) + try: + mqtt_data = get_mqtt_data(hass) + except KeyError as ex: + raise HomeAssistantError( + f"Cannot subscribe to topic '{topic}', " + "make sure MQTT is set up correctly" + ) from ex async_remove = await mqtt_data.client.async_subscribe( topic, catch_log_exception( diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index dc81e3d82b9..b071252ea64 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -959,6 +959,17 @@ async def test_subscribe_topic( unsub() +async def test_subscribe_topic_not_initialize( + hass: HomeAssistant, + mqtt_mock_entry: MqttMockHAClientGenerator, +) -> None: + """Test the subscription of a topic when MQTT was not initialized.""" + with pytest.raises( + HomeAssistantError, match=r".*make sure MQTT is set up correctly" + ): + await mqtt.async_subscribe(hass, "test-topic", record_calls) + + @patch("homeassistant.components.mqtt.client.INITIAL_SUBSCRIBE_COOLDOWN", 0.0) @patch("homeassistant.components.mqtt.client.UNSUBSCRIBE_COOLDOWN", 0.2) async def test_subscribe_and_resubscribe(