Go语言的测试框架主要有以下几种常见用法:
package main
import (
"testing"
)
func TestAddition(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Expected 5, but got %d", result)
}
}
package main
import (
"testing"
)
func BenchmarkAddition(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(2, 3)
}
}
package main
import "fmt"
func ExampleAddition() {
result := Add(2, 3)
fmt.Println(result) // 输出:5
}
$ go test -cover
coverage: 80.0% of statements
ok _/path/to/your/package 0.123s
package main
import (
"testing"
)
func TestAddition(t *testing.T) {
tests := []struct {
a, b int
want int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
for _, tt := range tests {
t.Run("", func(t *testing.T) {
if got := Add(tt.a, tt.b); got != tt.want {
t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
}
})
}
}
这些是Go语言测试框架的一些常见用法。通过使用这些方法,您可以确保代码的正确性和性能。