dongyumiao5210 2017-12-16 19:38
浏览 168
已采纳

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

I am doing some testing. I have a file 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
}

And a test file 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.
", "Load:", result)
    }
}

Here I test all 2 methods from Page, but after testing I see a message:

enter image description here

Why do I only get 85.7%? Where he get this numbers and how to get 100%?

  • 写回答

1条回答 默认 最新

  • dsoxcj7276 2017-12-16 19:57
    关注

    See "The Go Blog - The cover story"

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

    That would display an HTML representation of your source file, where you will clearly see which lines are or are not covered by your test.

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

    Other Go testing framework would show you the same visualization as well.
    Seee for instance GoConvey.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据