Testing 如何提高Go中的测试覆盖率?
我正在做一些测试。我有一个文件dao.go:Testing 如何提高Go中的测试覆盖率?,testing,go,Testing,Go,我正在做一些测试。我有一个文件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
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)
}
}
在这里,我从第页测试了所有2种方法,但测试后我看到一条消息:
为什么我只能得到85.7%的回报?他从哪里得到这些数字以及如何得到100%?参见“
这将显示源文件的HTML表示,您将清楚地看到哪些行被测试覆盖或未被测试覆盖
其他Go测试框架也会向您展示相同的可视化效果。例如,请参见,可能是因为您从未测试错误路径。你可能想,“如何获得100%?”不要。如果必须的话:撒谎。:-)请注意,这里的“plz”、“dunno”、“bout”(等)通常是下行投票的避雷针。这是一个相当可靠的指标(缺乏)的努力,进入一个职位。请用真话代替。非常感谢男士-不知道如何使用带有“html”标志的go工具封面
go test -coverprofile=coverage.out
go tool cover -html=coverage.out