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

藏色散人
Release: 2021-09-12 16:39:57
forward
1890 people have browsed it

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")
        }
Copy after login
  • 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")
        }
    }
Copy after login
  • 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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template