您的位置 首页 golang

golang 测试(testing)

在包目录内,所有以_test.go为后缀名的源文件并不是go build构建的一部分,它们是go test测试的一部分

1、单元测试

单元测试,是指对软件中的最小可测试单元进行检查和验证

 // 示例
// 新建helloword_test.go文件

import "testing"
// 格式:TestXxx(t *testing.T)
// 测试入口必须以Test开始,参数为 *testing.T。一个单元测试文件可以有多个测试入口
func TestHelloWord(t *testing.T)  {
	t.Log("hello world")
}

// 执行
// go test 后跟 helloworld_test.go 文件,表示测试这个文件里的所有测试用例
$ go test helloworld_test.go

// 显示测试结果,ok 表示测试通过,command-line-arguments 是测试用例需要用到的一个包名,0.012s 表示测试花费的时间
ok      command-line-arguments  0.012s
// -v 参数,显示详细的测试流程
$ go test -v helloworld_test.go
=== RUN   TestHelloWord
    word_test.go:8: hello world
--- PASS: TestHelloWord (0.00s)
=== RUN   TestSum
    word_test.go:14: 30
--- PASS: TestSum (0.00s)
PASS
ok      command-line-arguments  0.015s

// go test 指定文件时默认会执行文件内的所有测试用例。可以使用 -run 参数选择指定测试用例单独执行
$ go test -v -run TestSum helloworld_test.go
=== RUN   TestSum
    word_test.go:14: 30
--- PASS: TestSum (0.00s)
PASS
ok      command-line-arguments  0.012s

// 标记单元测试结果
// 示例
import (
	"fmt"
	"testing"
)

// 终止当前测试用例
func TestFailNow(t *testing.T) {
	t.FailNow()
}

// 只标记错误不终止测试
func TestFail(t *testing.T) {
	fmt.Println("before fail")
	t.Fail()
	fmt.Println("after fail")
}

// 运行
$ go test -v
=== RUN   TestHelloWord
    word_test.go:11: hello world
--- PASS: TestHelloWord (0.00s)
=== RUN   TestSum
    word_test.go:17: 30
--- PASS: TestSum (0.00s)
=== RUN   TestFailNow
--- FAIL: TestFailNow (0.00s)
=== RUN   TestFail
before fail
after fail                          // 调用 Fail() 后测试结果标记为失败,但是程序依然继续执行
--- FAIL: TestFail (0.00s)
FAIL
exit status 1
FAIL    test/test       0.021s  

2、基准测试

基准测试可以测试一段程序的运行性能及耗费 CPU 的程度。Go语言中提供了基准测试框架

原理:

基准测试框架对一个测试用例的默认测试时间是 1 秒。开始测试时,当以 Benchmark 开头的基准测试用例函数返回时还不到 1 秒,那么 testing.B 中的 N 值将按 1、2、5、10、20、50…递增,同时以递增后的值重新调用基准测试用例函数

 // 示例
// 新建benchmark_test.go文件

import "testing"
// 必须以Benchmark开头,参数为testing.B类型的指针
func BenchmarkAdd(b *testing.B) {
    // 在测试执行之前调用b.ResetTimer来重置时间,以便过滤掉测试之前代码所消耗的时间
    b.ResetTimer() // 重置计时器
	//b.StopTimer() // 停止计时器
	//b.StartTimer() // 开始计时器
	var n int
    // b.N 由基准测试框架提供
	for i := 0; i < b.N; i++ {
		n++
	}
}

// 运行
$ go test -bench=. -benchtime=5s -benchmem -run=none
goos: darwin
goarch: amd64
pkg: test/test
BenchmarkAdd-8          1000000000               0.283 ns/op           0 B/op          0 allocs/op
PASS
ok      test/test       0.325s

// 选项说明
-bench=. 表示运行 benchmark_test.go 文件里的所有基准测试(. 表示全部),类似单元测试中的-run
-run=none 表示过滤掉单元测试
benchtime=5s 表示的是运行时间为5s,默认的时间是1s
-benchmem 表示显示memory的指标

// 输出结果分析
goos: darwin        // 操作系统是darwin 
goarch: amd64       // 体系架构是amd64
BenchmarkAdd-8      // BenchmarkAdd表示运行的函数名称 8表示的是运行时对应的GOMAXPROCS的值
1000000000          // 1000000000表示次数,即testing.B 结构中提供给程序使用的 N
0.283 ns/op         // 表示执行一次函数,消耗的时间是0.283ns
0 B/op              // 每次执行操作,分配0B的内存
0 allocs/op         // 执行一次这个函数,分配内存的次数  

文章来源:智云一二三科技

文章标题:golang 测试(testing)

文章地址:https://www.zhihuclub.com/99103.shtml

关于作者: 智云科技

热门文章

网站地图