golang 测试,单元测试和基准测试

go test xxx.go

带 -v 表示冗余输出,成功pass的也会输出信息。

文件命名使用 xx_test.go 保存在项目目录里即可,也可以新建个test目录,TestAll

测试分为单元测试(功能)和基准测试(性能)。

单元测试函数名Test开头,接收一个指针型参数(*testing.T)。Example示例程序也算单元测试,不用接收参数。

go test -v -run="指定函数名"

// one_test.go
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

const checkMark = "\u2713" // 对号 %v
const ballotX = "\u2717"   // 错号

// 输出测试
func TestA(t *testing.T) {
	t.Log(checkMark, "测试成功,Logf")
	t.Error(ballotX, "失败了但继续,Errorf")
	t.Fatal(ballotX, "\t 失败了并终止,Fatalf, \\t是制表符")
	t.Log("运行不到这里了")
}

// 模拟服务器返回
func mockServer() *httptest.Server {
	f := func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		fmt.Fprintf(w, "success")
	}
	return httptest.NewServer(http.HandlerFunc(f))
}
func TestB(t *testing.T) {
	server := mockServer()
	defer server.Close()
	resp, _ := http.Get(server.URL)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	t.Log(checkMark, "GET内容:", string(body))

	//	func init(){ .. } 这里可以自建net/http服务器
	//    req,err := http.NewRequest()
	//    rw := httptest.NewRecorder()
	//    http.DefaultServeMux.ServeHTTP(rw,req)
	//    这样可以模拟外部访问,rw.Body就是内容了

}

// Example示例也是测试,如果返回结果和注释中的结果不一样,就会FAIL。
func ExampleC() {
	fmt.Println("233")
	//    Output:
	//    233
}

结果如下:

C:/Go/bin/go.exe test -v [C:/Users/pxlol/Desktop/demo]
=== RUN   TestA
--- FAIL: TestA (0.00s)
	2018_7_31_test.go:17: ✓ 测试成功,Logf
	2018_7_31_test.go:18: ✗ 失败了但继续,Errorf
	2018_7_31_test.go:19: ✗ 	 失败了并终止,Fatalf, \t是制表符
=== RUN   TestB
--- PASS: TestB (0.00s)
	2018_7_31_test.go:37: ✓ GET内容: success
=== RUN   ExampleC
--- PASS: ExampleC (0.00s)
FAIL
exit status 1
FAIL	_/C_/Users/pxlol/Desktop/demo	0.088s

基准测试以Benchmark开头,接收一个指针型参数(*testing.B)

go test -v -run="none" -bench=.    不允许单元测试,运行所有的基准测试,-bench可以指定函数名,支持正则。

-benchmem 表示分配内存的次数和字节数,-benchtime="3s" 表示持续3秒

// two_test.go
package main

import (
	"fmt"
	"strconv"
	"testing"
)

func BenchmarkA(b *testing.B) {
	number := 10
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		fmt.Sprintf("%d", number)
	}
}

func BenchmarkB(b *testing.B) {
	number := 10
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		strconv.Itoa(number)
	}
}

运行结果:

$ go test -v -bench=. -benchmem
goos: windows
goarch: amd64
BenchmarkA-4    20000000               122 ns/op              16 B/op          2 allocs/op
BenchmarkB-4    100000000               11.0 ns/op             0 B/op          0 allocs/op
PASS
ok      _/C_/Users/pxlol/Desktop/demo   3.791s

122ns/op 表示每次操作耗时122纳秒, 16B表示每次操作用了16字节,2 allocs表示每次操作分配内存2次。

猜你喜欢

转载自blog.csdn.net/hjmnasdkl/article/details/81304329