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

如何在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?

图片转代码服务由CSDN问答提供 功能建议

我目前正在寻找在Go中为net.Conn接口创建一些单元测试以及其他功能的方法 建立在该功能之上,我想知道在Google Go中进行单元测试的最佳方法是什么? 我的代码如下:

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

是最多的 测试此代码的有效方式以及使用这些功能的代码启动一个独立的goroutine以使其像服务器一样工作,请使用 net.http.httptest包,还是其他?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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

相关推荐 更多相似问题