dougong5285 2015-07-31 04:57
浏览 267

在测试函数中运行ListenAndServe()时,端口没有关闭,该如何解决?

When I call http.ListenAndServe() in a test function the port does NOT close even after the tests have finished and the process has terminated. So the next time I run the tests I get the error "ListenAndServe: listen tcp :8080: bind: address already in use".

This does not happen when I run my program normally through main().

func TestIndex(t *testing.T) {
  handle := handlers.ServeAndHandle("8080")
  req, _ := http.NewRequest("GET", "", nil)
  w := httptest.NewRecorder()
  handle.ServeHTTP(w, req)
  if w.Code != http.StatusOK {
      t.Errorf("Home page didn't return %v", http.StatusOK)
  }
}
// this is just a wrapper function of ListenAndServe. m is of type handler
func ServeAndHandle(port string) http.Handler {
  m := &mux{}
  err := http.ListenAndServe(":"+port, m) // set listen port
  if err != nil {
      log.Fatal("ListenAndServe: ", err)
  }
  return m
}
  • 写回答

1条回答 默认 最新

  • douzhang8033 2018-05-25 12:47
    关注

    You can use NewUnstartedServer to create a instance, start it manually then defer closing it at the end of the test. Something along the lines:

    ...
    ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {  
        fmt.Fprintln(w, "Hello world")
    }))
    
    l, _ := net.Listen("tcp", URL)
    ts.Listener = l
    ts.Start()
    defer ts.Close()
    
    res, err := http.Get(URL)  
    if err != nil {
      log.Fatal(err)
    } 
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?