Go 单元测试和基准测试

80 阅读1分钟

文件命名规则

首先测试文件命名必须以_test.go结尾,测试函数必须以Test为前缀进行命名

单元测试代码和调试方式

type Student struct {
	Name   string
	Age    int
	Gender int
}
type Class struct {
	ID      string
	Student []Student
}

var (
	s = Student{"zhangsan", 21, 3}
	c = Class{
		ID:      "2",
		Student: []Student{s, s},
	}
)

func TestJson(t *testing.T) {
	//json序列化
	bytes, err := json.Marshal(c)
	if err != nil {
		fmt.Println("json序列化失败", err)
		t.Fail()
	}
	// str := string(bytes)
	var c Class
	//json反序列化
	err = json.Unmarshal(bytes, &c)
	if err != nil {
		fmt.Println("json反序列化失败", err)
		t.Fail()
	}
	fmt.Println("json标准包测试完毕")
}

控制台输入go test json_test.go,结果为ok command-line-arguments 0.001s

如果想单独运行某个测试函数,可以使用 go test json_test.go -v -run=Json只要匹配到Json就会成功运行

基准测试代码和调试方式

基准测试主要是测试代码的性能

func BenchmarkJson(b *testing.B) {
	for i := 0; i < b.N; i++ {
		bytes, _ := json.Marshal(c)
		var c Class
		json.Unmarshal(bytes, &c)
	}
}

通过go test -bench=Json json_test.go运行基准测试程序