Go core development study notes (Nianqi) - Unit Testing

Unit test the effects: a function or a confirmation result of the introduction of package is correct.

Traditional method: whether the results of the test output and expected results are consistent,
have something to do on the production environment, to be effective, there is no such environmental test environment;
not conducive to the management, the need to test framework to solve the problem.

In Golang with a testing framework testing lightweight , Go Test test command to implement testing and performance testing unit (execution code takes time).
Solve the following problems by unit tests:

  1. Make sure that each function is run, and the results are output correctly.
  2. Write code to ensure performance is good
  3. A logic unit test can discover errors, use of program design and implementation of early exposure to locate the solution to the problem.
  4. Performance test focused on a number of issues on the programming, but also allows the program to remain stable at high concurrency.

Use unit testing

  1. Tested separately create a folder, and to main () running isolation test does not require the file main () entry.
  2. .Go function test file, extracted _test.go file, needs to import Testing _test.go package.

Example:

	package tst
	import "testing"

	func Test<dest>(t *testing.T) {
		//引入测试函数1
		//引入测试函数2
	}

Case Simulation: tst create a package, and then write two papers, Accumu.go and Accumu_test.go inside, two documents written as follows

Accumu.go

	//>>> Accumu.go <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	
	package tst
	
	func Accumu(n int) int {        //就是一个累加器,没啥说得,没有main()
		res := 0
		for i := 0 ; i <= n ; i++ {
			res += i
		}
		return res
	}                 

Accumu_test.go

	//>>> Accumu_test.go <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	//测试单个文件:切换到此目录下,go test -v会默认测试所有函数,如果只想测试其中一个,需要命令 go test -v Accumu_test.go Accumu.go
	//测试单个方法:切换到此目录下,需要命令 go test -v -test.run Accumu
	
	package tst

	import (
		"testing"       //需要导入testing包
	)

	func TestAccumu(t *testing.T) {    //在Goland中,默认test文件都会直接出此类格式
		res := Accumu(10)              //测试结果与res所传函数有关,与函数名无关
		if res != 55 {
			t.Fatalf("应输入值为%v,实际输出为%v",55,res)   //遇到错误即终止,并会反馈结果为FAIL
		}
		t.Logf("程序测试正确!")    //如果测试无异常则打印PASS,后面日志为t.logf()中的字符串内容
	}                   //关于测试结果,Goland中测试文件都会有一个红色箭头,因此无需黑屏终端go test命令来使用

Test results are as follows:

/*
e:\Golear\src\tst>go test -v
=== RUN   TestAccumu
--- PASS: TestAccumu (0.00s)
    cal_test.go:12: 程序测试正确!
PASS
ok      _/e_/Golear/src/tst     0.536s

e:\Golear\src\tst>go test -v -test.run Accumu
=== RUN   TestAccumu
--- PASS: TestAccumu (0.00s)
    cal_test.go:12: 程序测试正确!
PASS
ok      _/e_/Golear/src/tst     0.607s
*/

Serializing and deserializing unit tests + + file used in conjunction with the actual application:

Demand: Creating a structure: Heros
fields: Name string, Age int, Hobby string
method: Store () after the structure variable serialized saved to a file kunkun.txt in
RevStore () from the file structure variable kunkun.txt Summary read and deserialize
unit testing: testing the above-described two methods is normal.

:( core code segment assume as production, can not be easily tested)

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

type KunFamily struct {
	Name string `json:"name"`
	Age int `json:"age"`
	Hobby string `json:"hobby"`
}

func (k *KunFamily) Store() bool {       //为了确保测试,故返回布尔值
	slice, err := json.Marshal(k)
	if err != nil {
		fmt.Println("序列化失败,失败原因为: ",err)
		return false
	}

	file, err := os.OpenFile("D:/kunkun.txt", os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println("请检查错误为:", err)
		return false
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	_, _ = writer.WriteString(string(slice))
	_ = writer.Flush()
	return true
}

func (k *KunFamily) RevStore() bool {      //为了确保测试,故返回布尔值
	//读取文件
	file := "D:/kunkun.txt"
	content, err := ioutil.ReadFile(file)
	if err != nil {
		fmt.Println("读取错误,错误为:", err)
		return false
	}
	//反序列化
	err1 := json.Unmarshal([]byte(content), k)      //err := json.Unmarshal([]byte(string), &<struct结构体变量>)
	if err1 != nil {
		fmt.Println("反序列化出现异常,异常报错为:",err1)
		return false
	}
	return true
}

func main() {
	var caixukun1  = &KunFamily{"蔡徐坤1",20,"鸡你太美"}
	caixukun1.Store()
	caixukun1.RevStore()
}

Test file is written off from the production :( a code segment, x.go)

package tst
import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

type KunFamily struct {
	Name string `json:"name"`
	Age int `json:"age"`
	Hobby string `json:"hobby"`
}
func (k *KunFamily) Store() bool {
	slice, err := json.Marshal(k)
	if err != nil {
		fmt.Println("序列化失败,失败原因为: ",err)
		return false
	}

	file, err := os.OpenFile("D:/kunkun.txt", os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println("请检查错误为:", err)
		return false
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	_, _ = writer.WriteString(string(slice))
	_ = writer.Flush()
	return true
}
func (k *KunFamily) RevStore() bool {
	file := "D:/kunkun.txt"
	content, err := ioutil.ReadFile(file)
	if err != nil {
		fmt.Println("读取错误,错误为:", err)
		return false
	}

	err1 := json.Unmarshal([]byte(content), k)      //err := json.Unmarshal([]byte(string), &<struct结构体变量>)
	if err1 != nil {
		fmt.Println("反序列化出现异常,异常报错为:",err1)
		return false
	}
	return true
}

Written test file: (x_test.go)

package tst

import (
	"testing"
	)

func TestKunFamily_Store(t *testing.T) {
	var caixukun  = &KunFamily{"蔡徐坤1",20,"鸡你太美"}
	res := caixukun.Store()
	if res != true {
		t.Fatalf("测试失败")
	}
	t.Logf("程序测试正确!")
}

func TestKunFamily_RevStore(t *testing.T) {
	var caixukun  = &KunFamily{"蔡徐坤1",20,"鸡你太美"}
	res := caixukun.RevStore()
	if res != true {
		t.Fatalf("测试失败")
	}
	t.Logf("程序测试正确!")
}
Published 49 original articles · won praise 18 · views 3998

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/90477305