Go 语言学习手册
免费学习
完整知识体系
快速检索
Go语言学习手册《单元测试(testing 包)》:Go 内置 `testing` 包支持单元测试和基准测试。 **编写测试文件:** 后缀 `_test.go`,函数名以 `Test` 开头,参数 `*testing.T`。 ```go // math.go func Add(a, b...
测试与性能
单元测试(testing 包)
【详细说明 & 代码示例】
Go 内置 `testing` 包支持单元测试和基准测试。
**编写测试文件:** 后缀 `_test.go`,函数名以 `Test` 开头,参数 `*testing.T`。
```go
// math.go
func Add(a, b int) int { return a + b }
// math_test.go
package main
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
expected := 5
if result != expected {
t.Errorf("Add(2,3) = %d; want %d", result, expected)
}
}
```
**运行测试:** `go test` 或 `go test -v`。
**表驱动测试:**
```go
func TestAdd(t *testing.T) {
tests := []struct{ a, b, want int }{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
for _, tt := range tests {
got := Add(tt.a, tt.b)
if got != tt.want {
t.Errorf("Add(%d,%d) = %d; want %d", tt.a, tt.b, got, tt.want)
}
}
}
```
**基准测试(Benchmark):** 函数名以 `Benchmark` 开头,参数 `*testing.B`。
```go
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(1, 2)
}
}
```
运行:`go test -bench=.`
**覆盖率:** `go test -cover`。
学习提示:建议安装 Go 环境(go.dev/dl),使用 VS Code 或 GoLand 编写代码,并熟练使用 go run、go build、go mod 等命令。
全部章节目录(共 30 个知识点)
Go 基础 (1个知识点)
变量与数据类型 (2个知识点)
控制流程 (2个知识点)
结构体与方法 (2个知识点)
接口(interface) (1个知识点)
指针 (1个知识点)
错误处理 (1个知识点)
包管理 (1个知识点)
并发:goroutine (1个知识点)
并发:channel (1个知识点)
同步原语 (1个知识点)
标准库 (2个知识点)
网络与 HTTP (1个知识点)
测试与性能 (1个知识点)
反射与泛型 (1个知识点)
CGO 与汇编 (1个知识点)
Web 框架 (1个知识点)
数据库操作 (1个知识点)
配置与日志 (1个知识点)
部署与运维 (1个知识点)
设计模式 (2个知识点)
进阶技巧 (2个知识点)
使用说明
- • 本手册涵盖 Go 语言从基础到并发实战、Web 服务的完整知识体系
- • 在搜索框输入关键词,快速定位相关知识点
- • 点击条目标题进入详情页,查看详细说明与代码示例
- • 页面按分类展示所有知识点,方便系统性学习
- • 建议安装 Go 环境并使用 VS Code 或 GoLand 进行实践