| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package mqttbroker
- import (
- "testing"
- "time"
- mqtt "github.com/eclipse/paho.mqtt.golang"
- )
- // TestEmbedBrokerEcho 验证内嵌 broker 能启动,且 paho 客户端能连接、订阅、发布并收到回环消息。
- func TestEmbedBrokerEcho(t *testing.T) {
- const (
- listenAddr = ":18830"
- brokerAddr = "tcp://127.0.0.1:18830"
- )
- broker, err := Start(listenAddr)
- if err != nil {
- t.Fatalf("启动内嵌 broker 失败: %v", err)
- }
- defer func() { _ = broker.Close() }()
- opts := mqtt.NewClientOptions().AddBroker(brokerAddr).SetClientID("test-client")
- client := mqtt.NewClient(opts)
- if token := client.Connect(); token.Wait() && token.Error() != nil {
- t.Fatalf("客户端连接失败: %v", token.Error())
- }
- defer client.Disconnect(100)
- received := make(chan string, 1)
- if token := client.Subscribe("parking/test/echo", 1, func(_ mqtt.Client, msg mqtt.Message) {
- received <- string(msg.Payload())
- }); token.Wait() && token.Error() != nil {
- t.Fatalf("订阅失败: %v", token.Error())
- }
- if token := client.Publish("parking/test/echo", 1, false, "hello-broker"); token.Wait() && token.Error() != nil {
- t.Fatalf("发布失败: %v", token.Error())
- }
- select {
- case got := <-received:
- if got != "hello-broker" {
- t.Fatalf("回环内容不符: %s", got)
- }
- t.Logf("内嵌 broker 回环成功: %s", got)
- case <-time.After(5 * time.Second):
- t.Fatal("等待回环消息超时")
- }
- }
|