这是我参与「第五届青训营 」伴学笔记创作活动的第 2 天
一、本堂课重点内容:
- 底层并发 sync.Mutex
- 并发高级组件 channel、WaitGroup
go mod 依赖管理
go mod tidy 自动更新go.mod文件,采用最新版本,并下载到pkg文件夹
go的测试方法
二、详细知识点介绍:
单元测试: 具体到某个函数或功能,比较细节
go test --cover 可测试代码覆盖率,代码覆盖率即测试代码运行了实际代码的行数占总行数的百分比
测试文件以_test结尾,函数名以Test开头
package test
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestJudgePassLineTrue(t *testing.T) {
isPass := JudgePassLine(70)
assert.Equal(t, true, isPass)
}
func TestJudgePassLineFail(t *testing.T) {
isPass := JudgePassLine(50)
assert.Equal(t, false, isPass)
}
mock测试: 因网络或io等不确定性,或缺乏实际场景,采用mock手法将函数打桩替换掉,在测试过程中执行mock函数,执行完后清理现场并将函数替换回来
import (
"bou.ke/monkey"
"github.com/stretchr/testify/assert"
"testing"
)
func TestProcessFirstLine(t *testing.T) {
firstLine := ProcessFirstLine()
assert.Equal(t, "line00", firstLine)
}
func TestProcessFirstLineWithMock(t *testing.T) {
monkey.Patch(ReadFirstLine, func() string {
return "line110"
})
defer monkey.Unpatch(ReadFirstLine)
line := ProcessFirstLine()
assert.Equal(t, "line000", line)
}
基准测试,测试性能,每个操作耗时
go test bench=. 执行当前文件夹的全部基准测试函数
func BenchmarkSelect(b *testing.B) {
InitServerIndex()
b.ResetTimer()
for i := 0; i < b.N; i++ {
Select()
}
}
func BenchmarkSelectParallel(b *testing.B) {
InitServerIndex()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Select()
}
})
}
func BenchmarkFastSelectParallel(b *testing.B) {
InitServerIndex()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
FastSelect()
}
})
}
比如以上为串行与并行测试的测试函数,以Benchmark开头
项目实战讲解
分层架构
config为配置文件目录, 表结构在里面
controller :控制器层,只写客户端调用接口回调函数的基本逻辑,核心逻辑实现都在service实现
dao: 为数据库操作的封装,与数据库的底层操作的封装都在里面实现
Gin的基本使用与回调等