https://blog.csdn.net/u011957758/article/details/81267972
前言
每種語言都有自己的測試姿勢,golang的作者提供了一個testing的包來供大家完成測試之旅,簡單好用,一起走一波。
10s後以下知識點即將靠近:
1.爲什麼需要測試?
2.Golang的測試規矩
3.功能測試
4.壓力測試
5.測試代碼的覆蓋率測試
6.測試所有的參數備忘
正文
1.爲什麼需要測試?
這個是一個老生常談的話題了,忘記哪裏看的數據了,表明是完善的測試體系(這裏主要指自測),其實是會提高開發效率的。
當項目足夠複雜的時候,想要保證儘可能少的bug,兩種方式最有效:1.代碼審覈 2.測試。
所以Golang官方提供了testing包來滿足大家的需求。
2.Golang的測試規矩
通過testing包我們主要是可以進行三個測試的姿勢:1.功能測試 2.壓力測試 3.測試代碼覆蓋率的測試(你寫的測試用例覆蓋了多少代碼)。
在介紹以上三點之前,有一些Golang官方的一些約定(也可以說測試規矩)是需要遵守的,否則Golang是不承認你寫的測試代碼的。
關鍵點 | 說明 |
---|---|
導入需要的包 | import testing (如果你是goland,那麼可以忽略,因爲ide就自動幫你加上) |
執行命令 | go test file_test.go |
測試文件命名 | 必須以_test.go結尾 |
功能測試的用力函數 | 必須以Test開頭&&後頭跟着的函數名不能以小寫字母開頭,比如:Testcbs 就是不行的,TestCbs就是ok的 |
功能測試參數 | testing.T |
壓力測試用例函數 | 必須以Benchmark開頭&&其後的函數名不能以小寫字母開頭(例子同上) |
壓力測試參數 | testing.B |
測試信息 | .Log方法,默認情況下是不會顯示的,只有在go test -v的時候顯示 |
測試控制 | 通過Error/Errorf/FailNow/Fatal等來進行測試是否是失敗,或者在失敗的情況下的控制 |
壓力測試命令 | go test -test.bench file_test.go |
壓力測試的循環體 | 使用test.B.N |
3.功能測試
我是創建了一個文件夾gotest,裏頭存在兩個文件:1.正式文件cbstest.go 2.測試文件cbstest_test.go
上代碼:
cbstest.go
package gotest
// 根據長寬獲取面積
func GetArea(weight int, height int) int {
return weight*height
}
cbstest_test.go:
package gotest
import "testing"
func TestGetArea(t *testing.T) {
area := GetArea(40, 50)
if area != 2000 {
t.Error("測試失敗")
}
}
可以執行命令行:go test -v
獲取通過goland來執行:
4.壓力測試
cbstest_test.go改造代碼爲壓力測試:
package gotest
import "testing"
func BenchmarkGetArea(t *testing.B) {
for i := 0; i < t.N; i++ {
GetArea(40, 50)
}
}
goland執行後輸出結果:
命令行執行:go test -bench=.
5.測試代碼的覆蓋率測試
執行命令:go test -cover
在goland執行:
需要特別說明的是,測試的覆蓋度正常情況下是跑不滿100%,比如說寫的代碼是來接住panic的等等異常的,那其實就不會走到了。
6.測試所有的參數備忘
The test binary also accepts flags that control execution of the test; these
flags are also accessible by ‘go test’.
-bench regexp
Run only those benchmarks matching a regular expression.
By default, no benchmarks are run.
To run all benchmarks, use '-bench .' or '-bench=.'.
The regular expression is split by unbracketed slash (/)
characters into a sequence of regular expressions, and each
part of a benchmark's identifier must match the corresponding
element in the sequence, if any. Possible parents of matches
are run with b.N=1 to identify sub-benchmarks. For example,
given -bench=X/Y, top-level benchmarks matching X are run
with b.N=1 to find any sub-benchmarks matching Y, which are
then run in full.
-benchtime t
Run enough iterations of each benchmark to take t, specified
as a time.Duration (for example, -benchtime 1h30s).
The default is 1 second (1s).
-count n
Run each test and benchmark n times (default 1).
If -cpu is set, run n times for each GOMAXPROCS value.
Examples are always run once.
-cover
Enable coverage analysis.
Note that because coverage works by annotating the source
code before compilation, compilation and test failures with
coverage enabled may report line numbers that don't correspond
to the original sources.
-covermode set,count,atomic
Set the mode for coverage analysis for the package[s]
being tested. The default is "set" unless -race is enabled,
in which case it is "atomic".
The values:
set: bool: does this statement run?
count: int: how many times does this statement run?
atomic: int: count, but correct in multithreaded tests;
significantly more expensive.
Sets -cover.
-coverpkg pattern1,pattern2,pattern3
Apply coverage analysis in each test to packages matching the patterns.
The default is for each test to analyze only the package being tested.
See 'go help packages' for a description of package patterns.
Sets -cover.
-cpu 1,2,4
Specify a list of GOMAXPROCS values for which the tests or
benchmarks should be executed. The default is the current value
of GOMAXPROCS.
-failfast
Do not start new tests after the first test failure.
-list regexp
List tests, benchmarks, or examples matching the regular expression.
No tests, benchmarks or examples will be run. This will only
list top-level tests. No subtest or subbenchmarks will be shown.
-parallel n
Allow parallel execution of test functions that call t.Parallel.
The value of this flag is the maximum number of tests to run
simultaneously; by default, it is set to the value of GOMAXPROCS.
Note that -parallel only applies within a single test binary.
The 'go test' command may run tests for different packages
in parallel as well, according to the setting of the -p flag
(see 'go help build').
-run regexp
Run only those tests and examples matching the regular expression.
For tests, the regular expression is split by unbracketed slash (/)
characters into a sequence of regular expressions, and each part
of a test's identifier must match the corresponding element in
the sequence, if any. Note that possible parents of matches are
run too, so that -run=X/Y matches and runs and reports the result
of all tests matching X, even those without sub-tests matching Y,
because it must run them to look for those sub-tests.
-short
Tell long-running tests to shorten their run time.
It is off by default but set during all.bash so that installing
the Go tree can run a sanity check but not spend time running
exhaustive tests.
-timeout d
If a test binary runs longer than duration d, panic.
If d is 0, the timeout is disabled.
The default is 10 minutes (10m).
-v
Verbose output: log all tests as they are run. Also print all
text from Log and Logf calls even if the test succeeds.
-vet list
Configure the invocation of "go vet" during "go test"
to use the comma-separated list of vet checks.
If list is empty, "go test" runs "go vet" with a curated list of
checks believed to be always worth addressing.
If list is "off", "go test" does not run "go vet" at all.
The following flags are also recognized by ‘go test’ and can be used to
profile the tests during execution:
-benchmem
Print memory allocation statistics for benchmarks.
-blockprofile block.out
Write a goroutine blocking profile to the specified file
when all tests are complete.
Writes test binary as -c would.
-blockprofilerate n
Control the detail provided in goroutine blocking profiles by
calling runtime.SetBlockProfileRate with n.
See 'go doc runtime.SetBlockProfileRate'.
The profiler aims to sample, on average, one blocking event every
n nanoseconds the program spends blocked. By default,
if -test.blockprofile is set without this flag, all blocking events
are recorded, equivalent to -test.blockprofilerate=1.
-coverprofile cover.out
Write a coverage profile to the file after all tests have passed.
Sets -cover.
-cpuprofile cpu.out
Write a CPU profile to the specified file before exiting.
Writes test binary as -c would.
-memprofile mem.out
Write a memory profile to the file after all tests have passed.
Writes test binary as -c would.
-memprofilerate n
Enable more precise (and expensive) memory profiles by setting
runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
To profile all memory allocations, use -test.memprofilerate=1
and pass --alloc_space flag to the pprof tool.
-mutexprofile mutex.out
Write a mutex contention profile to the specified file
when all tests are complete.
Writes test binary as -c would.
-mutexprofilefraction n
Sample 1 in n stack traces of goroutines holding a
contended mutex.
-outputdir directory
Place output files from profiling in the specified directory,
by default the directory in which "go test" is running.
-trace trace.out
Write an execution trace to the specified file before exiting.