Traditional test:
package main import ( "fmt" ) func addUpper(n int) int { res := 0 for i := 0; i <= n; i++ { res += i } return res } func main() { res := addUpper(10) if res != 55 { fmt.Printf("错误,真实值:%v,期望值:%v", res, 55) } else { fmt.Printf (" Correct, true value:% v, the expected value:% v " , RES, 55 ) } }
Problems: (1) the need to modify the main function, if the program is running, the need to stop the procedure; (2) a plurality of functions to be tested, step more complicated;
Unit Test: (1) ensure that each function is run, and the results are correct operation; (2) write code to ensure good performance;
Use go in testing package: test to TestXxx functions that begin, note that the first X is capitalized.
The overall test flow chart:
Specific catalog:
main.go
package main
func main() {
}
pro.go
package utils func addUpper(n int) int { res := 0 for i := 0; i <= n; i++ { res += i } return res } func sub(n1 int, n2 int) int { return n1 - n2 }
add_test.go
utils Package Import ( " FMT " " Testing " ) FUNC TestAddUpper (T * testing.T) { RES: = addUpper ( 10 ) IF ! RES = 55 { // program error input, exit, and output log t.Fatalf ( " AddUpper (10) performs error expected value =% v, the output value V% = " , 55 , RES) } // if correct, the output log t.Logf ( " AddUpper (10) executed correctly ... " ) } FUNC TestHello (T * testing.T) { fmt.Println ("hello world") }
sub_test.go
utils Package Import " Testing " FUNC the TestSub (T * testing.T) { RES: = Sub ( 20 is , 10 ) IF ! RES = 10 { // program error input, exit, and output log t.Fatalf ( " Sub ( 20,10) execution error expected value =% v, the output value V% = " , 10 , RES) } // if correct, the output log t.Logf ( " Sub (20,10) execute properly ... " ) }
final result:
Unit Testing Note:
(1) test function must TestXxx command, wherein the first upper case X;
(2) test case files must _test.go end;
(3) TestXxx (t * testing.T) parameter type must be * testing.T;
(4) a test case file can have multiple test cases;
(5) run a test case instructions:
go test (run correctly without log output error log)
go test -v (whether or not correct, all output log)
(6) When an error occurs, you may be used to format t.Fatalf output an error message and exits the program;
(7) t.logf () may output a corresponding log;
(8) PASS represented by the test, FAIL indicates a failure;
(9) Testing a single file: go test -v add_test.go pro.go
(10) a single Test Method: go test -v -test.run TestAddUpper