1、单元测试 + Mock 测试 + 基准测试
加上 -gcflags=all=-l gomonkey 库就不会受到内联优化的干扰
package main
import "strconv"
type ST struct {
}
func Hello() string {
return "Hello"
}
func MockFunction(id int) string {
return "MockFunction:" + strconv.Itoa(id)
}
func (t *ST) MockMethod(id int) string {
return "MockMethod:" + strconv.Itoa(id)
}
package main
import (
"fmt"
"reflect"
"testing"
"github.com/agiledragon/gomonkey"
"github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
)
func TestMain(m *testing.M) {
// Before
fmt.Println("Before")
m.Run()
// After
fmt.Println("After")
}
func TestHello(t *testing.T) {
assert.Equal(t, "Hello", Hello())
}
func TestMockFunctionAndMockMethod(t *testing.T) {
convey.Convey("MockFunction", t, func() {
// mock func
patches := gomonkey.ApplyFunc(MockFunction, func(int) string {
return "mock-function"
})
defer patches.Reset()
assert.Equal(t, "mock-function", MockFunction(10086))
// mock method
patches = gomonkey.ApplyMethod(reflect.TypeOf(&ST{}), "MockMethod", func(t *ST, id int) string {
return "mock-method"
})
defer patches.Reset()
st := &ST{}
assert.Equal(t, "mock-method", st.MockMethod(10086))
})
}
func BenchmarkRand(b *testing.B) {
// init
b.ResetTimer()
for i := 0; i < b.N; i++ {
rand.Intn(1000)
}
}
func BenchmarkParallel(b *testing.B) {
// init
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
rand.Intn(1000)
}
})
}