如何为MQTT客户端编写测试? [英] How do I write tests for an MQTT client?

查看:267
本文介绍了如何为MQTT客户端编写测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MQTT和测试的新手,不确定两者如何配合工作.

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

我正在使用 mqtt.js ,并希望编写一些基本测试.我应该如何构造它们?更具体地说,我需要模拟MQTT代理,还是可以建立实时连接?该连接应该连接到HiveMQ等测试服务,还是连接到我自己设置的代理?

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?

我的设置:

我正在构建一个聊天应用程序.

I'm building a chat application.

3个Docker容器. 1个经纪人(使用 mosquitto ,2个客户端.

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

客户端在脚本中使用mqtt.js,该脚本作为网页的一部分加载,该网页用作在聊天室中输入和阅读消息的前端.加载客户端脚本后,将使用默认消息主题与代理建立连接.

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.

使用Mocha/Chai进行测试

Using Mocha/Chai for testing

index.js =>通过webpack捆绑到"bundle.js"中,并通过HTML加载到脚本标签中

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')
})

推荐答案

通常,您不想测试其他服务,它们负责自己的测试.您只想测试代码执行的工作单元.

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. 它能否正确处理连接失败
  2. 它能否正确处理连接成功
  3. 它是否正确解析消息有效负载(json?)
  4. 它可以正确处理格式错误的有效负载.

等等....

但是,您可以为代理编写负载/压力测试.我使用paho python客户端来测试集群,并执行负载/压力测试(使用gatlin).

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).

这篇关于如何为MQTT客户端编写测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆