Home >Backend Development >Golang >Step by step analysis of how to write GO project test

Step by step analysis of how to write GO project test

藏色散人
藏色散人forward
2021-09-12 16:39:161886browse

This article is introduced by the go language tutorial column to introduce how to write golang project test. I hope it will be helpful to friends in need!

How to write golang project test

  • 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.

More For golang related knowledge, please visit the golangtutorial column!

The above is the detailed content of Step by step analysis of how to write GO project test. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete