Go测试

编程 · 02-22 · 150 人浏览

Go语言自带一个轻量级测试框架testing和go test命令来实现单元测试(T类型)和性能测试(B类型)。

单元测试

表格驱动测试

main.go

package main

import (
  "math"
)

func triangle(a, b int) int {
  c := int(math.Sqrt(float64(a*a + b*b)))
  return c
}

func main() {
  a, b := 3, 4
  c := triangle(a, b)
  println(c)
}

main_test.go

package main

import "testing"

func TestTriangle(t *testing.T) {
  tests := []struct{ a, b, c int }{
    {3, 4, 5},
    {5, 12, 13},
    {8, 15, 17},
    {12, 35, 37},
    {30000, 40000, 50000},
  }

  for _, tt := range tests {
    if actual := triangle(tt.a, tt.b); actual != tt.c {
      t.Errorf("triangle(%d, %d): "+
        "got %d; expected %d",
        tt.a, tt.b, actual, tt.c)
    }
  }
}

性能测试

Go
Theme Jasmine by Kent Liao