gpt4 book ai didi

testing - 如何提高 Go 中的测试覆盖率?

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:38 26 4
gpt4 key购买 nike

我正在做一些测试。我有一个文件 dao.go:

package model_dao
import "io/ioutil"
const fileExtension = ".txt"
type Page struct {
Title string
Body []byte
}
func (p Page) SaveAsFile() (e error) {
p.Title = p.Title + fileExtension
return ioutil.WriteFile(p.Title, p.Body, 0600)
}
func LoadFromFile(title string) (*Page, error) {
fileName := title + fileExtension
body, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
return &Page{title, body}, nil
}

还有一个测试文件dao_test.go:

package model_dao_test
import (
"shopserver/model/dao"
"testing"
)
func TestDAOFileWorks(t *testing.T) {
TITLE := "test"
BODY := []byte("Hello, World!!")
p := &model_dao.Page{TITLE, BODY}
p.SaveAsFile()
p, _ = model_dao.LoadFromFile(TITLE)
result := p.Body
if string(BODY) != string(result) {
t.Error("Body", BODY, "saved.\n", "Load:", result)
}
}

我在这里测试了 Page 中的所有 2 个方法,但在测试之后我看到一条消息:

enter image description here

为什么我只得到 85.7%?他从哪里获得这些数字以及如何获得 100%?

最佳答案

参见“The Go Blog - The cover story

go test -coverprofile=coverage.out 
go tool cover -html=coverage.out

这将显示您的源文件的 HTML 表示形式,您可以在其中清楚地看到您的测试覆盖或未覆盖哪些行。

https://blog.golang.org/cover/set.png

其他 Go 测试框架也会向您显示相同的可视化效果。
参见例如 GoConvey .

关于testing - 如何提高 Go 中的测试覆盖率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47849300/

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