问题
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 ...
- Does it handle a connection failure correctly
- Does it handle a connection success correctly
- Does it parse the message payload (json?) correctly
- 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