This is a creation in Article, where the information may have evolved or changed.
Go Unit Test
Brief introduction
Unit testing is the complete feature provided by the Go language level, the test code is *_test.go named, the case of the unit test begins with a Test performance test case to Benchmark begin with, and the test command runs:go test <test_file_list>
Example
Implement permutation and combination functions and corresponding unit tests and performance tests
Create a project directory structure
Directory structure description See specification-Project
└── src └── hmath ├── hmath.go └── hmath_test.go
implementing permutation and combination functions
// src/hmath/hmath.gopackage hmathfunc combination(m, n int) int { if n > m-n { n = m - n } c := 1 for i := 0; i < n; i++ { c *= m - i c /= i + 1 } return c}
Implementing unit Tests and performance tests
Src/hmath/hmath_test.gopackage hmathimport ("Math/rand" "testing")//unit test//test global function to TestFunction name//test class member function to TE Stclass_function named Func testcombination (T *testing. T) {//define a temporary structure here to store the parameters of the test case and the expected return value for _, Unit: = range []struct {m int n int Expected int} {1, 0, 1}, {4, 1, 4}, {4, 2, 6}, {4, 3, 4}, {4, 4, 1}, {1 0, 1, 10}, {10, 3, 120}, {10, 7, 120},} {//Call permutation combination function, match the expected result, if inconsistent output error if actually: = Co Mbination (UNIT.M, UNIT.N); Actually! = unit.expected {T.errorf ("combination: [%v], actually: [%v]", Unit, actually)}}}//performance test Func benchmarkcombination (b *testing. B) {//B.N will take a suitable value depending on the run time of the function for I: = 0; i < B.N; i++ {combination (i+1, Rand. INTN (i+1))}}//Concurrency test func benchmarkcombinationparallel (b *testing. B) {//Test an object or function under a multithreaded scenario for safe B.runparallel (func (Pb *testing). PB) {for PB. Next () {m: =Rand. INTN (+) + 1 N: = rand. INTN (m) combination (M, n)})}
Run unit tests and performance tests
export GOPATH=$(pwd)go test src/hmath/*.go # 单元测试go test --cover src/hmath/*.go # 单元测试覆盖率go test -bench=. src/hmath/*.go # 性能测试
The output of the above command is as follows:
hatlonely@localhost: ~/hatlonely/github/tmp $ go test src/hmath/hmath*.gook command-line-arguments 0.005shatlonely@localhost: ~/hatlonely/github/tmp $ go test --cover src/hmath/hmath*.gook command-line-arguments 0.005s coverage: 100.0% of statementshatlonely@localhost: ~/hatlonely/github/tmp $ go test -bench=. src/hmath/*.goBenchmarkCombination-8 100000 217618 ns/opBenchmarkCombinationParallel-8 3000000 401 ns/opPASSok command-line-arguments 23.599s