Golang单元测试中的技巧是什么
package main
import (
"fmt"
"testing"
"github.com/agiledragon/gomonkey/v2"
"go-demo/m/unit-test/other/rand"
)
func init() {
gomonkey.ApplyFunc(rand.Number, func() int { return 666 })
}
func TestRand(t *testing.T) {
fmt.Println(rand.Number())
}
var numbers = []int{
100,
1000,
77777,
666666,
}
func BenchmarkPrimeNumbers(b *testing.B) {
for _, v := range numbers {
b.Run(fmt.Sprintf("calc_num_%d", v), func(b *testing.B) {
for i := 0; i < b.N; i++ {
primeNumbers(v)
}
})
}
}
package main
import (
"testing"
)
func TestAdd(t *testing.T) {
tests := []struct {
a, b, expected int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
{-1, -1, -2},
}
for _, test := range tests {
result := Add(test.a, test.b)
if result != test.expected {
t.Errorf("Add(%d, %d) = %d; expected %d", test.a, test.b, result, test.expected)
}
}
}
func Add(a, b int) int {
return a + b
}