golang 测试退出状态 -1 并且什么也不显示

lee*_*per 6 testing go

最近我一直在 golang 中开发一个 Restful 应用程序,当我尝试在不同的子目录中编写测试时发生了奇怪的事情。我的项目结构是:

\n\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 handlers/\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 defs.go\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 hello_test.go\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 hello.go\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 server/\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 codes.go\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 middlewares_test.go\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 middlewares.go\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 utility/\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 auth.go\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 auth_test.go\n
Run Code Online (Sandbox Code Playgroud)\n\n

handlers/ 中的所有文件都声明为“包处理程序”,server/ 中的所有文件都声明为“包服务器”,依此类推。当我在 utility/ 和 handlers/ 中运行 go test 时,一切都很好。但是如果我在 server/ 中运行 go test,它只会返回:

\n\n
[likejun@localhost server]$ go test\nexit status 1\nFAIL    server_golang/server    0.003s\n
Run Code Online (Sandbox Code Playgroud)\n\n

似乎它在运行之前就以代码 1 退出,有人能告诉我为什么会发生这种情况吗?谢谢,我已经花了整个下午了。

\n\n

middleware_test.go 中的代码

\n\n
package server\n\nimport (\n    "io"\n    "net/http"\n    "net/http/httptest"\n    "testing"\n)\n\nfunc TestHello(t *testing.T) {\n    req, err := http.NewRequest(http.MethodGet, "/", nil)\n    if err != nil {\n        t.Fatal(err)\n    }\n\n    rec := httptest.NewRecorder()\n\n    func(w http.ResponseWriter, r *http.Request) {\n        w.WriteHeader(http.StatusOK)\n        w.Header().Set("Content-Type", "application/json")\n        io.WriteString(w, `{"hello": "world"}`)\n    }(rec, req)\n\n    if status := rec.Code; status != http.StatusOK {\n        t.Errorf("handler returned wrong status code: got %d want %d", status, http.StatusOK)\n    }\n\n    if rec.Header().Get("Content-Type") != "application/json" {\n        t.Errorf("handler returned wrong content type header: got %s want %s", rec.Header().Get("Content-Type"), "application/json")\n    }\n\n    expected := `{"hello": "world"}`\n    if rec.Body.String() != expected {\n        t.Errorf("handler returned unexpected body: got %s want %s", rec.Body.String(), expected)\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n