mardi 28 février 2017

golang test exit status -1 and shows nothing

Recently I've been working on a Restful app in golang, strange things happened when I try to write tests in different subdirectories. My project structure is:

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

All files in handlers/ are declared "package handlers", all files in server/ are declared "package server", and so on. When I run go test in utility/ and handlers/ everything is fine. But if I run go test in server/, it returns me nothing but just:

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

It seems that it exits with a code 1 before even run, could someone tells me why this happened? Thank you, I've been spent the whole afternoon on it.

the code in 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)
    }
}

Aucun commentaire:

Enregistrer un commentaire