一尘不染

在golang中为ws创建单元测试

go

我使用大猩猩Web套接字框架,并使用以下客户端在本地运行Web套接字并对其进行调试

https://github.com/gorilla/websocket

ws = new WebSocket("ws://localhost:8080/mypath")
ws.onmessage = function(ev) { console.log(ev.data) }
ws.send("hello")

当我在chrome控制台中使用它时此方法有效,但是我的问题是是否有一种方法可以进行一些单元测试并避免使用chrome控制台?


阅读 356

收藏
2020-07-02

共1个答案

一尘不染

使用net / http /
httptest
软件包创建一个测试服务器。使用Gorilla客户端连接到该服务器。读取和写入消息以测试连接。

package main

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{}

func echo(w http.ResponseWriter, r *http.Request) {
    c, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        return
    }
    defer c.Close()
    for {
        mt, message, err := c.ReadMessage()
        if err != nil {
            break
        }
        err = c.WriteMessage(mt, message)
        if err != nil {
            break
        }
    }
}

func TestExample(t *testing.T) {
    // Create test server with the echo handler.
    s := httptest.NewServer(http.HandlerFunc(echo))
    defer s.Close()

    // Convert http://127.0.0.1 to ws://127.0.0.
    u := "ws" + strings.TrimPrefix(s.URL, "http")

    // Connect to the server
    ws, _, err := websocket.DefaultDialer.Dial(u, nil)
    if err != nil {
        t.Fatalf("%v", err)
    }
    defer ws.Close()

    // Send message to server, read response and check to see if it's what we expect.
    for i := 0; i < 10; i++ {
        if err := ws.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
            t.Fatalf("%v", err)
        }
        _, p, err := ws.ReadMessage()
        if err != nil {
            t.Fatalf("%v", err)
        }
        if string(p) != "hello" {
            t.Fatalf("bad message")
        }
    }
}
2020-07-02