broker_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package mqttbroker
  2. import (
  3. "testing"
  4. "time"
  5. mqtt "github.com/eclipse/paho.mqtt.golang"
  6. )
  7. // TestEmbedBrokerEcho 验证内嵌 broker 能启动,且 paho 客户端能连接、订阅、发布并收到回环消息。
  8. func TestEmbedBrokerEcho(t *testing.T) {
  9. const (
  10. listenAddr = ":18830"
  11. brokerAddr = "tcp://127.0.0.1:18830"
  12. )
  13. broker, err := Start(listenAddr)
  14. if err != nil {
  15. t.Fatalf("启动内嵌 broker 失败: %v", err)
  16. }
  17. defer func() { _ = broker.Close() }()
  18. opts := mqtt.NewClientOptions().AddBroker(brokerAddr).SetClientID("test-client")
  19. client := mqtt.NewClient(opts)
  20. if token := client.Connect(); token.Wait() && token.Error() != nil {
  21. t.Fatalf("客户端连接失败: %v", token.Error())
  22. }
  23. defer client.Disconnect(100)
  24. received := make(chan string, 1)
  25. if token := client.Subscribe("parking/test/echo", 1, func(_ mqtt.Client, msg mqtt.Message) {
  26. received <- string(msg.Payload())
  27. }); token.Wait() && token.Error() != nil {
  28. t.Fatalf("订阅失败: %v", token.Error())
  29. }
  30. if token := client.Publish("parking/test/echo", 1, false, "hello-broker"); token.Wait() && token.Error() != nil {
  31. t.Fatalf("发布失败: %v", token.Error())
  32. }
  33. select {
  34. case got := <-received:
  35. if got != "hello-broker" {
  36. t.Fatalf("回环内容不符: %s", got)
  37. }
  38. t.Logf("内嵌 broker 回环成功: %s", got)
  39. case <-time.After(5 * time.Second):
  40. t.Fatal("等待回环消息超时")
  41. }
  42. }