unit-testing - API中的测试覆盖率

标签 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
我想了解这里发生的事情,因为它没有涵盖任何内容。有人知道解释吗?

最佳答案

我发现了我的错误:
我正在尝试使用以下命令运行测试范围:

$ 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语句。谢谢大家,如果打扰到别人,我感到抱歉。

关于unit-testing - API中的测试覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62883090/

相关文章:

javascript - 如何测试用户界面小部件?

json - 如何将 JSON 响应值与 Postman 环境变量匹配?

Android:如何在两个测试代码上使用 Mock?

json - 使用一些已知和一些未知的字段名解码 JSON

go - Go 函数参数中的后递增运算符,不可能吗?

reflection - reflect.Value 的字符串方法无法按预期工作

java - 运行 JTestR 示例需要什么? (或根本不使用 JTestR)

c - 单元测试kill命令

android - 为什么 Gradle 能够模拟 final类?

Android - Assertj Android - 运行错误