单元测试和基准测试 | 青训营

220 阅读1分钟

单元测试用于检测一个函数的正确性。

基准测试用于检测一个函数的性能。

1. 单元测试

  1. 单元测试规范:
  • 函数名以TestXxx开头,参数为testing.T
  • 测试文件为xxx_test.go
  1. 单元测试指令:
 go test xxx_test.go [-v] [-run=正则表达式]
  • -v:允许有print输出(默认忽视print)
  • -run:执行符合匹配的测试函数(默认所有测试函数)

json

json包测试指令:

 go test json_test.go -v

测试代码:

 type Student struct {
     Name   string
     Age    int
     Gender bool
 }
 ​
 type Class struct {
     Id       string
     Students []Student
 }
 ​
 func TestJson(t *testing.T) {
     s := Student{"小明", 20, true}
     c := Class{"1班", []Student{s, s, s}}
     bytes, err := json.Marshal(c)
     if err != nil {
         t.Fail()
     }
 ​
     var c2 Class
     err = json.Unmarshal(bytes, &c2)
     if err != nil {
         t.Fail()
     }
 ​
     if !(c2.Id == c.Id && len(c.Students) == len(c2.Students)) {
         t.Fail()
     }
     fmt.Println("json包通过测试")
 }
 ​

2. 基准测试

  1. 基准测试规范:
  • 函数名以BenchmarkXxx开头,参数为testing.B
  • 函数内部执行循环,次数为b.N
  • 测试文件为xxx_test.go
  1. 单元测试指令:
 go test xxx_test.go [-bench=正则表达式] [-benchmem]
  • -bench:执行符合匹配的测试函数(默认所有测试函数)
  • -benchmem:打印内存相关的消耗

Json

测试指令:

 go test .\sonic_test.go -bench=Json -benchmem       #json库
 go test .\sonic_test.go -bench=Sonic -benchmem      #sonic库

测试代码:

 type Student struct {
     Name   string
     Age    int
     Gender bool
 }
 ​
 type Class struct {
     Id       string
     Students []Student
 }
 ​
 var (
     s = Student{"小明", 20, true}
     c = Class{"1班", []Student{s, s, s}}
 )
 ​
 func BenchmarkJson(b *testing.B) {
     for i := 0; i < b.N; i++ {
         bytes, _ := json.Marshal(c)
         var c2 Class
         json.Unmarshal(bytes, &c2)
     }
 }
 ​
 func BenchmarkSonic(b *testing.B) {
     for i := 0; i < b.N; i++ {
         bytes, _ := sonic.Marshal(c)
         var c2 Class
         sonic.Unmarshal(bytes, &c2)
     }
 }
 ​