Go 语言工程实践之测试|青训营笔记
Go语言工程实践之测试
程序的测试阶段可分为回归测试、集成测试和单元测试三个模块。从回归测试到单元测试是覆盖率逐层变大的,成本逐渐降低的。对于我们编码工作中单元测试是很重要的内容。
单元测试
单元测试是各个函数模块功能进行测试,可以创建不同的测试案例,已验证功能实现的正确性
-
单元测试规则
- 所有的单元测试文件都以
XXXX_test.go结尾. func TestXxx(*testing T)作为测试函数编写模板- 初始化逻辑放到
TestMain函数中
- 所有的单元测试文件都以
-
Code Example:
// 1. hello.go 文件Code
package hello
func HelloTom() string {
return "Jeryy"
}
// 2. hello_test.go 文件Code
package hello
import (
"os"
"testing"
)
func TestHeloTom(t *testing.T) {
output := HelloTom()
expectOutput := "Tom"
if output != expectOutput {
t.Errorf("Expected %s do not match actual %s", expectOutput, output)
}
}
func TestMain(m *testing.M) {
//测试前初始化工作
code := m.Run()
//测试后,
os.Exit(code)
}
// 3.运行go test 命令即可进行单元测试
还可以使用 assert进行单元测试 Code Example:
// 1.hello.go 文件Code
参照上文
// 2. hello_test.go 文件Code
package hello
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func TestHeloTom(t *testing.T) {
output := HelloTom()
expectOutput := "Jeryy"
assert.Equal(t, expectOutput, output)
}
func TestMain(m *testing.M) {
//测试前初始化工作
code := m.Run()
//TesTHeloTom()
//测试后,
os.Exit(code)
}
// 3.运行go test 命令即可进行单元测试
单元测试-覆盖率
衡量代码是否经过了足够的测试. 评价项目的测试水准. 评估项目带啊吗是否达到了高水准测试等级.
example:
// 1. score.go 文件代码
package hello
func JudgePassLine(score int16) bool {
if score >= 60 {
return true
}
return false
}
// 2. score_tset.go 文件代码
package hello
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func TestJudgePassLineTrue(t *testing.T) {
isPass := JudgePassLine(70)
assert.Equal(t, true, isPass)
}
func TestMain(m *testing.M) {
//测试前初始化工作
code := m.Run()
//TesTHeloTom()
//测试后,
os.Exit(code)
}
// 3.运行指令
go test score_test.go score.go --cover
单元测试-依赖
编码工作有时候会依赖一些文件,数据库等内容才能进行测试。 使用 monkey 可以摆脱对文件的依赖,使得测试在各个环境下都能运行。 单元测试-文件处理 不使用monkey代码
// read_frist.go
package hello
import (
"bufio"
"os"
"strings"
)
func ReadFirstLine() string {
open, err := os.Open("log")
defer open.Close()
if err != nil {
return ""
}
scanner := bufio.NewScanner(open)
for scanner.Scan() {
return scanner.Text()
}
return ""
}
func ProcessFirstLine() string {
line := ReadFirstLine()
destLine := strings.ReplaceAll(line, "11", "00")
return destLine
}
// read_frist_tset.go
package hello
import (
"bou.ke/monkey"
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func TestProcessFirstLineWithMock(t *testing.T) {
monkey.Patch(ReadFirstLine, func() string { //使用monkey代替输入
return "line00"
})
defer monkey.Unpatch(ReadFirstLine)
firstLine := ProcessFirstLine()
assert.Equal(t, "line00", firstLine)
}
func TestMain(m *testing.M) {
coder := m.Run()
os.Exit(coder)
}
// go test readFirst_test.go readFirst.go --cover
感想
测试是成熟项目的重要步骤,之前自己独立做一些Demo的时候都没有注意测试这个,导致我的代码只能我调,而且自己也是凭经验来调试,不成体系。这次学习带来很大收益。