This is a creation in Article, where the information may have evolved or changed.
Generally, in order to ensure the stability of the entire system, it is often necessary to write a large number of unit tests, such as Java junit,php PHPUnit and so on provide similar functionality. The testing package in Golang provides the functionality of this test, which is handy when combined with the Go Test tool.
Unit tests in Golang not only feature tests, but also performance tests, which are very powerful.
Functional Testing
In the SRC directory of Golang, create a new directory for math, the test directory structure is as follows:
Golang Unit Test Catalog
Fibonacci.go code is as follows, there is a Fibonacci function mainly
package lib //斐波那契数列//求出第n个数的值func Fibonacci(n int64) int64 { if n < 2 { return n } return Fibonacci(n-1) + Fibonacci(n-2)
Fibonacci_test.go is the test file, Golang need to test the file all with "_test" end, the test function is used to start with the code as follows:
package lib import ( "testing") func TestFibonacci(t *testing.T) { r := Fibonacci(10) if r != 55 { t.Errorf("Fibonacci(10) failed. Got %d, expected 55.", r) }}
Test this program with the Go test
$ go test lib ok lib 0.008s
If you are prompted to not find the package, add the code path to the environment variable Gopath.
can't load package: package lib: cannot find package "lib" in any of:
Performance testing
In combination with the above method, the performance of the function is tested here, and if you need to perform a performance test, the function starts with benchmark.
//性能测试func BenchmarkFibonacci(b *testing.B) { for i := 0; i < b.N; i++ { Fibonacci(10) }}
Next, perform this performance test:
$ go test -bench=. lib PASS BenchmarkFibonacci 5000000 436 ns/op ok lib 2.608s
The second line of output indicates that the function ran 5 million times, and the average time to run it was 436ns.
This performance test only tests the case with a parameter of 10. You can test multiple parameters if you need to:
//测试参数为5的性能func BenchmarkFibonacci5(b *testing.B) { for i := 0; i < b.N; i++ { Fibonacci(5) }} //测试参数为20的性能func BenchmarkFibonacci20(b *testing.B) { for i := 0; i < b.N; i++ { Fibonacci(20) }}
Run it:
$ go test -bench=. lib PASS BenchmarkFibonacci 5000000 357 ns/op BenchmarkFibonacci5 100000000 29.5 ns/op BenchmarkFibonacci20 50000 44688 ns/op ok lib 7.824s
If there are a lot of ways to test performance, it will take longer. You can set the number of performance test rows that need to run through the-bench= parameter:
$ go test -bench=Fibonacci20 lib PASS BenchmarkFibonacci20 50000 44367 ns/op ok lib 2.677s