MQTT

Commercial

About MQTT

MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe messaging protocol designed for constrained devices and low-bandwidth, high-latency networks. It uses a broker-based architecture where clients publish messages to topics and subscribe to topics of interest. MQTT is widely used in IoT (Internet of Things), mobile applications, and scenarios requiring minimal network overhead. It supports three Quality of Service (QoS) levels for message delivery guarantees.

Using MQTT in AsyncAPI Specifications

To define MQTT-based messaging in your AsyncAPI specification, you need to declare a server with the mqtt protocol and reference it in your channels.

Server Definition

servers:
  mqttServer:
    host: "tcp://localhost:1884"
    protocol: "mqtt"
    description: "MQTT server"

The host should point to your MQTT broker address with the protocol prefix (typically tcp:// or ssl:// for secure connections).

Channel Definition

channels:
  NewOrderPlaced:
    address: "new-orders"
    servers:
      - $ref: "#/servers/mqttServer"
    messages:
      placeOrder.message:
        $ref: "#/components/messages/OrderRequest"

The address field specifies the MQTT topic name. MQTT supports hierarchical topics using forward slashes (e.g., orders/new or orders/cancelled). Reference the MQTT server in the servers array to indicate this channel uses MQTT as the transport protocol.

Message Definition

MQTT messages typically include the payload and can embed correlation information:

components:
  messages:
    OrderRequest:
      contentType: "application/json"
      payload:
        type: "object"
        properties:
          orderCorrelationId:
            type: "string"
          # ... other payload properties

Note: Unlike protocols with native header support, MQTT typically requires correlation IDs to be part of the message payload.

Running Contract Tests with Specmatic-Async

Specmatic-async enables you to run contract tests against applications using MQTT by validating that your service correctly implements the AsyncAPI specification.

For a complete working example of MQTT contract testing with Specmatic-Async, refer to the specmatic-async-sample project.

Step 1: Configure specmatic.yaml

Create or update your specmatic.yaml file to include the AsyncAPI specification:

version: 2
contracts:
  - provides:
      - specs:
          - spec/spec.yaml
        specType: asyncapi

Step 2: Start MQTT Infrastructure

Use Docker Compose to start an MQTT broker (Mosquitto):

services:
  mosquitto:
    image: eclipse-mosquitto:2.0
    ports:
      - "1884:1884"
    volumes:
      - ./mosquitto/config:/mosquitto/config
      - ./mosquitto/data:/mosquitto/data
      - ./mosquitto/log:/mosquitto/log

Create a basic Mosquitto configuration file at mosquitto/config/mosquitto.conf:

listener 1884
allow_anonymous true

Start the infrastructure:

docker compose up -d

Step 3: Run Your Application

Start your application that implements the AsyncAPI specification. The application should be configured to connect to the MQTT broker and subscribe to/publish on the topics defined in your contract.

Step 4: Run Contract Tests

Execute the contract tests using the Specmatic Docker image:

docker run --network host -v "$PWD/specmatic.yaml:/usr/src/app/specmatic.yaml" -v "$PWD/spec:/usr/src/app/spec" specmatic/specmatic-async test

Specmatic-async will:

  1. Read the AsyncAPI specification and identify MQTT channels
  2. Connect to the configured MQTT broker
  3. Publish test messages to your application’s subscribed topics
  4. Validate that your application publishes correct responses to output topics
  5. Verify that message payloads and correlation IDs conform to the contract

Step 5: Review Test Results

Check the test output for detailed validation results, including any contract violations or failures.

Tips for MQTT Testing

  • QoS Levels: Use QoS 1 or 2 for tests requiring delivery guarantees; QoS 0 for performance testing
  • Client IDs: Use unique client IDs for each test instance to avoid connection conflicts
  • Retained Messages: Be cautious with retained messages in tests as they persist on the broker
  • Topic Wildcards: MQTT supports wildcards (+ for single level, # for multiple levels) in subscriptions
  • Clean Session: Set clean session flag appropriately for test isolation
  • Correlation in Payload: Since MQTT doesn’t have native headers, include correlation IDs in the JSON payload
  • Connection Keep-Alive: Configure appropriate keep-alive intervals for stable test connections
  • SSL/TLS: Use secure connections (ssl://) for production-like testing