go单元测试
go test -v ./... -coverprofile=vtgotestcover.out
go测试结果导出html:
gocov convert vtgotestcover.out |gocov-html >coverage.htmlgo导出所有测试结果:
go tool cover -html=c.out
单元测试实例
store.go
package monster
import (
"encoding/json"
"io/fs"
"io/ioutil"
"log"
)
var f = "d:/monster.json"
type Monster struct {
Name string
Age int
Skill string
}
func (m *Monster) Store() error {
ms, err := json.Marshal(m)
if err != nil {
log.Fatalf("mashal error:%v", err)
return err
}
if err := ioutil.WriteFile(f, ms, fs.ModePerm); err != nil {
log.Fatalf("Write file error:%v", err)
return err
}
return err
}
func (m *Monster) ReStore() *Monster {
f, err := ioutil.ReadFile(f)
if err != nil {
log.Fatalf("ReadFile error:%v", err)
return nil
}
monster := &Monster{}
err = json.Unmarshal(f, monster)
if err != nil {
log.Fatalf("Unmarshal error:%v", err)
return nil
}
return monster
}
store_test.go
package monster_test
import (
"lch-tests/monster"
"testing"
)
func TestStore(t *testing.T) {
monster := &monster.Monster{
Name: "konglong",
Age: 100000,
Skill: "kill human",
}
monster.Store()
mStored := monster.ReStore()
if mStored.Name != "konglong" {
t.Fatalf("不是预期效果! 单元测试不通过!")
} else {
t.Logf("well done!")
}
}
运行结果
go test -v -test.run TestStore
=== RUN TestStore
store_test.go:19: well done!
--- PASS: TestStore (0.00s)
PASS
ok my-tests/monster_test 0.228s