golang测试退出状态-1并且不显示任何内容

时间:2017-03-01 07:51:26

标签: testing go

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

├── handlers/
│   ├── defs.go
│   ├── hello_test.go
│   ├── hello.go
├── server/
│   ├── codes.go
│   ├── middlewares_test.go
│   ├── middlewares.go
├── utility/
│   ├── auth.go
│   ├── auth_test.go

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

[likejun@localhost server]$ go test
exit status 1
FAIL    server_golang/server    0.003s

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

middleware_test.go中的代码

package server

import (
    "io"
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestHello(t *testing.T) {
    req, err := http.NewRequest(http.MethodGet, "/", nil)
    if err != nil {
        t.Fatal(err)
    }

    rec := httptest.NewRecorder()

    func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Header().Set("Content-Type", "application/json")
        io.WriteString(w, `{"hello": "world"}`)
    }(rec, req)

    if status := rec.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %d want %d", status, http.StatusOK)
    }

    if rec.Header().Get("Content-Type") != "application/json" {
        t.Errorf("handler returned wrong content type header: got %s want %s", rec.Header().Get("Content-Type"), "application/json")
    }

    expected := `{"hello": "world"}`
    if rec.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %s want %s", rec.Body.String(), expected)
    }
}

0 个答案:

没有答案