普通单元测试
$ cd $GOPATH/src
$ mkdir leetcode
$ cd leetcode
$ echo '
package leetcode
func TwoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, num := range nums {
key := target - num
if j, ok := m[key]; ok {
return []int{j, i}
}
m[nums[i]] = i
}
return []int{}
}' > two_sum.go
$ echo '
package leetcode
import "testing"
func TestTwoSum(t *testing.T) {
t.Log(TwoSum([]int{2, 7, 11, 15}, 9))
}' > two_sum_test.go
注意:文件名格式必须是name_test.go,测试函数名称必须以Test开头,并且传入参数必须是*testing.T,格式如下:
func TestName(t *testing.T) {
// ...
}
test suite 测试
// Basic imports
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
// Define the suite, and absorb the built-in basic suite
// functionality from testify - including a T() method which
// returns the current testing context
type ExampleTestSuite struct {
suite.Suite
VariableThatShouldStartAtFive int
}
// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func (suite *ExampleTestSuite) SetupSuite() {
suite.VariableThatShouldStartAtFive = 5
}
func (suite *ExampleTestSuite) TearDownSuite() {
suite.VariableThatShouldStartAtFive = 5
}
// All methods that begin with "Test" are run as tests within a
// suite.
func (suite *ExampleTestSuite) TestExample() {
assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
suite.Equal(5, suite.VariableThatShouldStartAtFive)
}
// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestExampleTestSuite(t *testing.T) {
suite.Run(t, new(ExampleTestSuite))
}
定义结构体
SetupSuite(): test初始化操作,相当于test suite的构造函数
TeardownSuite(): 相当于test suite的析构函数
TestExampleTestSuite(t *testing.T): 程序测试入口
TestXXX(): 不同单元测试的函数
go test 单个文件或函数
go test 测试单个文件: go test -v hello_test.go hello.go
注意: go test 单个文件,一定要带上依赖的文件!!!这是因为运行go test时,go默认将源码文件和测试文件编译成一个临时执行文件,函数只能在这个临时文件中寻找。
go test 测试单个函数: go test -v -test.run TestRefreshAccessToken
refrence
https://blog.csdn.net/leonpengweicn/article/details/32334137
https://godoc.org/github.com/stretchr/testify/suite
http://objcoding.com/2018/09/14/go-test/