go 中测试 `net/http` 服务需避免在测试文件中定义 `main()` 函数,应使用以 `test` 开头的函数,并确保测试文件与主代码同属 `package main`,且不引入包名冲突。
在 Go 项目中(如名为 beacon 的 Web 应用),常见的测试错误源于对 Go 测试机制的误解:测试文件不是可执行程序,而是由 go test 工具驱动的测试套件。因此,beacon_test.go 中绝不能包含 func main() —— 这会与 beacon.go 中的 main() 冲突,导致编译失败(main redeclared);同时,测试文件也必须与源文件处于同一包(通常是 package
main),否则会触发 found packages main and xxx 错误。
✅ 正确做法如下:
例如,假设 beacon.go 包含一个简单 HTTP 处理器:
// beacon.go
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "OK")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}对应的标准测试应写为:
// beacon_test.go
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status OK; got %v", w.Code)
}
if w.Body.String() != "OK" {
t.Errorf("expected body 'OK'; got %q", w.Body.String())
}
}⚠️ 注意事项:
遵循以上结构,即可安全、高效地为 Go Web 应用编写可维护的 HTTP 单元测试。