How do I write tests for an MQTT client?

天大地大妈咪最大 提交于 2020-01-04 07:25:12

问题


I'm new to MQTT and testing and am unsure how the two should work together.

I'm using mqtt.js and want to write some basic tests. How should I structure them? More specifically, do I need to mock the MQTT broker, or can I make a live connection? Should that connection be to a test service like HiveMQ, etc, or to the broker I'm setting up myself?

My setup:

I'm building a chat application.

3 docker containers. 1 broker (using mosquitto, 2 clients.

Clients are using mqtt.js within a script that loads as part of a webpage which serves as a front-end for inputing and reading messages in the chat. When the client script is loaded, a connection is made to the broker with a default message topic.

I've been able to successfully connect and verify that the client can send and receive messages, but writing the app for proper testing has my eyeballs crossed.

Using Mocha/Chai for testing

index.js => gets bundled by webpack into 'bundle.js' and loaded by HTML within a script tag

// index .js
// gets bundled by wepback and loaded within a script tag in browser

const mqtt = require('mqtt')
const client = mqtt.connect('mqtt://localhost:9001')

client.on('connect', function () {
  console.log(process.env.NAME + ' has connected')
  client.publish('welcome', 'this is a message')
})

回答1:


Typically you don't want to test other services, they are responsible for their own testing. You only want to test the units of work your code does.

So yes, you may want to mock the broker/connection response objects to test:

The areas to verify could be ...

  1. Does it handle a connection failure correctly
  2. Does it handle a connection success correctly
  3. Does it parse the message payload (json?) correctly
  4. Does it handle an malformed payload correctly.

etc.....

You can, however, write load/stress tests for the brokers. I use the paho python client to test clustering, and perform load/stress tests (with gatlin).



来源:https://stackoverflow.com/questions/42230094/how-do-i-write-tests-for-an-mqtt-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!