基本的单元测试
代码语言:go复制func TestHello(t *testing.T) {
re := Hello()
want := "hello world"
if re == want {
t.Logf("hello()= %v, want %v", re, want)
} else {
t.Errorf("hello() =%v, want %v", re, want)
}
}
go test -v ./... -coverprofile=cover.out
go tool cover -html=cover.out -o coverage_xxxxx.html
常见的方法
一组测试定义list
代码语言:go复制[]struct {
name string
want string
}{
// TODO: Add test cases.
{
name: "test for hello",
want: "hello world",
},
}
三方库goconvey
代码语言:txt复制import(
. "github.com/smartystreets/goconvey/convey"
)
func TestAdd(t *testing.T) {
Convey("test add", t, func() {
Convey("1 2", func() {
So(Add(1, 2), ShouldEqual, 3)
})
Convey("-1 0", func() {
So(Add(-1, 0), ShouldEqual, -1)
})
})
}
goconvey -port 8181
http的mock
代码语言:txt复制. "bou.ke/monkey"
代码语言:txt复制. "github.com/smartystreets/goconvey/convey"
db的mock
代码语言:txt复制"github.com/gin-gonic/gin"
代码语言:txt复制. "github.com/smartystreets/goconvey/convey"
代码语言:txt复制"github.com/DATA-DOG/go-sqlmock"
代码语言:txt复制"github.com/jinzhu/gorm"
bench
go test -v -bench=.
go test -v -bench=. -benchmem