Home >Backend Development >Golang >How to write golang unit test

How to write golang unit test

(*-*)浩
(*-*)浩Original
2019-12-28 09:35:472610browse

How to write golang unit test

The go language attaches great importance to unit testing, not to mention the background of other authors, open source libraries, third-party support, etc., there are two points The point that allows me to pay attention to the GO language about unit testing is:

让 让 语 源 让 让 让 让 让 让 让 让 让 让 让 让 (Recommended Learning: go

)

The Go language comes with unit testing commands

From these two points, I think testing plays a very important role in the Go language, so in this article, I Also try to talk about Go language unit testing.

Writing Go unit test code

Go's testing method seems relatively low-level. It relies on the command go test and some test functions that can be run with go test. Write a convention. However, I think this is the so-called Go style. Since using Go, my feeling is that the Go language is a language that maintains the C language programming habits.

Golang language provides a set of unit test writing specifications. Let’s briefly demonstrate this writing method

How to write golang unit test

## Unit test files must end with .go

The test function is very simple

calc.go

package main
 
func add(a, b int) int {
	return a + b
}

calc_test.go

package main
 
import "testing"
 
func TestAdd(t *testing.T) {
r := add(2, 4)
if r != 6 {
t.Fatalf("add(2, 4) error, expect:%d, actual:%d", 6, r)
}
t.Logf("test add succ")
}

The above is the detailed content of How to write golang unit test. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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