- Business code
package main import "fmt" func sum(a int,b int) int { return a+b } func main() { fmt.Println("hello test") }
- test test case
package main import ( "fmt" "testing" ) func TestSum(t *testing.T) { var a = 3 var b =4 res :=sum(a,b) fmt.Printf("%d 与%d之和:为%d",a,b,res) if res != 7{ t.Error("error") } }
Each test file must import a test.
Each test case under the test file must start with Test and conform to the TestXxx format , otherwise go test will directly select the test and not execute it.
-
go test will automatically look for the test file in the directory, go test -v will display the execution process in detail
The input parameter of test case is t testing.T or b testing.B
t.Error is to print error information, and The current test case will be skipped
t.SkipNow() means to skip the test and directly press PASS to process the next test, and must be written in the first line of the test case, otherwise Invalid
go's test does not guarantee that multiple TestXxx are executed sequentially, but they are usually executed in order. In order to ensure sequential execution, you can use t.Run(name string, f func) to ensure sequential execution
TestMain(m *testing.M) as the initialization test, and use m.Run() to call other tests to complete some tests that require initialization operations, such as Database connection, file opening, REST service login, if m.Run() is not called in testMain, other test cases except TestMain will not be executed.