Go 学习笔记13.编写测试

编写测试要求

  • 文件名命名 xx_test.go
  • 测试函数命名 TestXxx开头 Xxx首字母大写
  • 函数参数 *test.T 类型

需要测试的程序源码

animal.go

package animal

import "fmt"

// Cat猫 结构体
type Cat struct {
	Name  string
	Color string
	Age   uint
}

// 一个初始化Cat的入口函数
func NewCat(name,color string,age uint) *Cat {
	return &Cat{name,color,age}
}

func (c *Cat) Sleeping() {
	fmt.Println(c.Color,"Cat",c.Name,"is sleeping")
}

func (c *Cat) Eating() {
	fmt.Println(c.Color,"Cat",c.Name,"is eating")
}

func (c *Cat) Print() {
	fmt.Print(c)
}

单元测试

animal_test.go

package animal

import "testing"

func TestCat_Sleeping(t *testing.T) {
	c := NewCat("Tom","blue",10)
	c.Sleeping()
}

func TestCat_Eating(t *testing.T) {
	c := NewCat("sinmigo","block",10)
	c.Eating()
	if c.Color == "white" {
		t.Log("Eating 测试通过")
	} else {
		t.Error("Eating 测试不通过")
	}
}

执行测试

go test -v -cover
--- PASS: TestCat_Sleeping (0.00s)
=== RUN   TestCat_Eating
block Cat sinmigo is eating
    TestCat_Eating: animal_test.go:16: Eating 测试不通过
--- FAIL: TestCat_Eating (0.00s)
FAIL
coverage: 75.0% of statements
exit status 1
FAIL    animal  1.898s

性能测试

animal_test.go

// 性能测试
func BenchmarkCat_Eating(b *testing.B) {
	c := NewCat("Tom","blue",10)

	for i :=0;i<b.N; i++ {
		c.Eating()
	}
}

执行

go test -bench=.
blue Cat Tom is sleeping
block Cat sinmigo is eating
goos: windows
goarch: amd64
pkg: animal
BenchmarkCat_Eating-8           1000000000               0.306 ns/op
PASS
ok      animal  3.062s
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章