我正在Go语言中学习测试,并且一直在尝试使用自己创建的API测量测试覆盖率:
main.go
package main
import (
"encoding/json"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", SimpleGet)
log.Print("Listen port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
// SimpleGet return Hello World
func SimpleGet(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
}
w.Header().Set("Content-Type", "application/json")
data := "Hello World"
switch r.Method {
case http.MethodGet:
json.NewEncoder(w).Encode(data)
default:
http.Error(w, "Invalid request method", 405)
}
}
测试:
main_test.go
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestSimpleGet(t *testing.T) {
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
SimpleGet(w, req)
resp := w.Result()
if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("handler returned wrong header content-type: got %v want %v",
resp.Header.Get("Content-Type"),
"application/json")
}
if status := w.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
expected := `"Hello World"`
if strings.TrimSuffix(w.Body.String(), "\n") != expected {
t.Errorf("handler returned unexpected body: got %v want %v", w.Body.String(), expected)
}
}
我运行go test
没问题,测试已经通过。但是,当我尝试获得测试覆盖率时,我得到了以下HTML:
我想了解这里发生的事情,因为它没有涵盖任何内容。有人知道要解释吗?