gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:44:10 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com