goconvey is a test framework for Golang, which can manage and run test cases, provides rich assertion functions, and supports many web interface features.
Guide package
import “github.com/smartystreets/goconvey”
Core API
Top-level Convey: It consists of test description, testing.T, and behavior functions.
Convey(description string, t *testing.T, action func())
Other layers Convey:
Convey(description string, action func())
Value assertion: Determine whether the actual value meets expectations.
func So(actual any, assert Assertion, expected ...any)
actual: actual value.
Assertion: assertion condition, generally composed of ShouldXXX,
expect: expected value.
convey running order
Traverse through the tree structure
Convey A
So 1
Convey B
So 2
Convey C
So 3
Execution order: 1 A->B, 2 A->C
code example
1. Test x++
func TestGetSumScore(t *testing.T) {
Convey("start x is 0", t, func() {
x := 0
Convey("x++", func() {
x++
So(x, ShouldEqual, 1)
})
})
}
2. Use multi-level nesting: test the GetSumScore function
GetSumScore function implementation:
type Student struct {
ID int64
Name string
Age int8
Major string
Score int
}
// 返回这些学生的分数总和
func GetSumScore(students []Student) int {
total := 0
for _, v := range students {
total += v.Score
}
return total
}
Test code:
func TestGetSumScore(t *testing.T) {
convey.Convey("init students", t, func() {
students := []Student{
{
Name: "yi", Score: 90},
{
Name: "w", Score: 100},
}
score := GetSumScore(students)
convey.Convey("GetSumScore", func() {
convey.So(score, convey.ShouldEqual, 190)
})
convey.Convey("Change students[0].score", func() {
students[0].Score = 10
score := GetSumScore(students)
convey.So(score, convey.ShouldEqual, 110)
})
})
}