dpt8910 2015-06-06 23:49
浏览 168
已采纳

如何在Golang的单元测试中测试net.Conn?

I'm currently looking into creating some unit tests for net.Conn interface in Go, as well as other functions that build up on top of that functionality, and I'm wondering what is the best way to unit test that in Google Go? My code looks like:

conn, _:=net.Dial("tcp", "127.0.0.1:8080")
...
fmt.Fprintf(conn, "test")
...
buffer:=make([]byte, 100)
conn.Read(buffer)

Is the most efficient way of testing this code and the code that uses these functions to spin up a separate goroutine to act like the server, use net.http.httptest package, or something else?

  • 写回答

3条回答 默认 最新

  • dqkf36241 2015-06-15 06:43
    关注

    Although it will depend on the implementation details of your particular case, the general approach will be to start a server (in a separate goroutine, as you already hinted), and listen to the incoming connections.

    For example, let's spin up a server and verify that the content we are reading from the connection is indeed the one we send over from the client:

    func TestConn(t *testing.T) {
        message := "Hi there!
    "
    
        go func() {
            conn, err := net.Dial("tcp", ":3000")
            if err != nil {
                t.Fatal(err)
            }
            defer conn.Close()
    
            if _, err := fmt.Fprintf(conn, message); err != nil {
                t.Fatal(err)
            }
        }()
    
        l, err := net.Listen("tcp", ":3000")
        if err != nil {
            t.Fatal(err)
        }
        defer l.Close()
        for {
            conn, err := l.Accept()
            if err != nil {
                return
            }
            defer conn.Close()
    
            buf, err := ioutil.ReadAll(conn)
            if err != nil {
                t.Fatal(err)
            }
    
            fmt.Println(string(buf[:]))
            if msg := string(buf[:]); msg != message {
                t.Fatalf("Unexpected message:
    Got:\t\t%s
    Expected:\t%s
    ", msg, message)
            }
            return // Done
        }
    
    }
    

    Note that here I'm not starting the server in the goroutine, as otherwise the test case is likely to be finished before the listener has run the test.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题