09 Unit Test

Article Directory


Go reason comes with a lightweight testing framework testing and comes with the go test command to implement unit testing and performance testing. Function testing can be performed based on the testing framework, or stress testing can be performed.
Writing method

  1. Write test case files such as: main_test.go
  2. import testing package, and write test case methods such as: func TestSum (t *testing.T)
  3. Execute the command go test -v to run the test case
    sample code
//测试用例文件
package main

import(
	"fmt"
	"testing"
)
func TestAddUpper( t *testing.T){
    
    
	res:=AddUpper(10)
	fmt.Println("结果=>",res)
	if res == 55{
    
    
		fmt.Println("准确")
	}else{
    
    
		fmt.Println("不准确")
	}
}

func TestSum( t *testing.T){
    
    
	res:=Sum(10,11)
	fmt.Println("结果=>",res)
	if res == 20{
    
    
		fmt.Println("准确")
		t.Logf("Sum() 方法测试通过")
	}else{
    
    
		fmt.Println("不准确")
		t.Fatalf("Sum() 方法期望返回 %v 实际返回 %v",20,res)
	}
}
package main

import(
	//"fmt"
	//"testing"
)
func main(){
    
    
	
}

func AddUpper(n int) int{
    
    
	res:=0
	for i:=1;i<=n;i++{
    
    
		res+=i
	}
	return res
}
func Sum(a int,b int) int{
    
    
	return a+b
}

important point

  1. The test case file name must end with _test.go, such as main_test.go
  2. The test case function must start with Test. Generally speaking, Test+The name of the function being tested is such as: TestSum
  3. TestSum (t *testing.T) The formal parameter of the test case function must be of type *testing.T
  4. A test case file can contain multiple test case functions,
  5. The go test command runs the test case. If the operation is correct, the log will not be displayed. If the operation error occurs, the log will appear.
    go test -v will output the log regardless of whether the operation is correct or incorrect.
  6. When an error occurs, you can use tFatalf to format the output error message and exit the program
  7. The t.Logf method can output logs
  8. All methods in all files are executed by default. If you want to test a single file, you need to pass parameters
    go test -v main_test.go main.go to
    test a single method go test -v -run TestSum

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/115273993