API 中的测试覆盖率

Test coverage in API

我正在学习 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:

我想了解这里发生了什么,因为它没有涵盖任何内容。有谁知道解释一下吗?

我发现了我的错误:

我正在尝试 运行 使用这些命令的测试覆盖率:

$ go test -run=Coverage -coverprofile=c.out
$ go tool cover -html=c.out

但正确的命令是:

$ go test -coverprofile=c.out
$ go tool cover -html=c.out

结果:

OBS:我又写了一个测试来涵盖所有 switch 语句。谢谢大家,如有打扰请见谅。