如何保证代码的质量和可靠性?Golang自带了testing包可用来实现测试用例和性能测试.
如下为例,新建gotest项目目录,编写两个文件bubblesort.go和bubblesort_test.go
bubblesort.go
package gotest
//from small to big
func BubbleSort(num []int) {
flag := false
for i := 0; i < len(num)-1; i++ {
flag = false
for j := 0; j < len(num)-1-i; j++ {
if num[j] > num[j+1] {
num[j], num[j+1] = num[j+1], num[j]
flag = true
}
}
if !flag {
break
}
}
return
}
package gotest
import (
"testing"
)
func TestBubbleSort(t *testing.T) {
values := []int{5, 4, 3, 2, 1}
BubbleSort(values)
if values[0] != 1 || values[1] != 2 || values[2] != 3 || values[3] != 4 ||
values[4] !=5 {
t.Error("BubbleSort() failed. Got", values, "Expected 1 2 3 4 5")
}
}
func BenchmarkBubbleSort(b *testing.B) {
for i := 0; i < b.N; i++ {
values := []int{5, 4, 3, 2, 1}
BubbleSort(values)
}
}
PASS
ok test/gotest 0.002s
=== RUN TestBubbleSort
--- PASS: TestBubbleSort (0.00s)
PASS
ok test/gotest 0.002s
$ go test -cover
PASS
coverage: 90.0% of statements
ok test/gotest 0.001s
$ go test -test.bench=".*"
PASS
BenchmarkBubbleSort-4 30000000 45.8 ns/op
ok test/gotest 1.424s