This is a creation in Article, where the information may have evolved or changed.
1. Introduction
The go language comes with a lightweight test framework testing and its own go test commands for unit testing and performance testing.
2. Requirements
- The file name must end With ' _test.go ' so that it executes to the corresponding code when executing ' Go test '
- You must import ' testing ' this bag
- All test case functions must start with ' test '
- The tests are executed in the order in which they were written in the source code.
- The parameter of the test function ' testxxx () ' is ' testing. T ', we can use this type to log errors or test status
- Test format: ' Func testxxx (t *testing. T) ', ' Xxx ' section can be any combination of alphanumeric, but the first letter cannot be a lowercase letter [a-z], such as ' Testintdiv ' is the wrong function name.
- function, by calling ' testing. T ' Error ', ' Errorf ', ' failnow ', ' Fatal ', ' fatalif ' method, means that the test does not pass, and the call ' Log ' method is used to record the information of the test.
3. Case studies
Gotest.go
Package Gotestimport ( "errors") Func division (A, B float64) (Float64, Error) { if0 { return0, errors. New (" divisor cannot be 0") } return A/ B, nil}
View Code
Gotest_test.go
Package Gotestimport ("Testing") func test_division_1 (t*testing. T) {ifI, E: = Division (6,2); I! =3|| E! =Nil {t.error ("The Division function test didn't pass .") } Else{T.Log ("The first Test passes")}}func test_division_2 (t*testing. T) {T.error ("just don't pass .")}
View Code
4. Stress testing
- The stress test case must follow the following format, where XXX can be a combination of any alphanumeric, but the first letter cannot be a lowercase letter
- Func benchmarkxxx (b *testing. B) {...}
- Go test does not perform the stress test function by default, if you want to perform a stress test with parameter-test.bench, syntax:-test.bench= "Test_name_regex", such as Go test-test.bench= ". *" Means testing all the stress test functions
- In the stress test case, remember to use testing in the loop body. B.N to allow the test to run correctly the file name must also end with _test.go
5. Case studies
Webbench_test.go
package gotestimport ( " testing ) func Benchmark_division (b *testing. B) { for I: = 0 ; i < B.N; I++ {Division ( 4 , 5 )}}func Benchmark_timeconsumingfunction (b *testing. B) {B.stoptimer () B.starttimer () for I: = 0 ; i < B.N; I++ {Division ( 4 , 5
View Code
Command line execution: Go.exe test-test.bench=.*