API中的测试覆盖率

时间:2020-07-13 19:40:22

标签: unit-testing go testing code-coverage

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

0% coverage

我想了解这里发生的事情,因为它没有涵盖任何内容。有人知道要解释吗?

1 个答案:

答案 0 :(得分:1)

我发现了我的错误:

我正在尝试使用以下命令来运行测试范围:

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

但是正确的命令是:

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

结果:

60% coverage

OBS:我再编写一个测试以涵盖所有switch语句。谢谢大家,对不起打扰了我。

相关问题