Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
返回教程列表

测试与调试

编写可靠的测试代码,掌握调试技巧

2 课时
1

单元测试

Go 内置了强大的测试框架。测试文件以 _test.go 结尾,测试函数以 Test 开头。

编写单元测试

go
1package main
2
3import "testing"
4
5func Add(a, b int) int {
6 return a + b
7}
8
9func TestAdd(t *testing.T) {
10 result := Add(2, 3)
11 expected := 5
12
13 if result != expected {
14 t.Errorf("Add(2, 3) = %d; want %d", result, expected)
15 }
16}
17
18// 表驱动测试
19func TestAddTableDriven(t *testing.T) {
20 tests := []struct {
21 name string
22 a, b int
23 expected int
24 }{
25 {"positive", 2, 3, 5},
26 {"negative", -1, -2, -3},
27 {"zero", 0, 0, 0},
28 }
29
30 for _, tt := range tests {
31 t.Run(tt.name, func(t *testing.T) {
32 result := Add(tt.a, tt.b)
33 if result != tt.expected {
34 t.Errorf("got %d, want %d", result, tt.expected)
35 }
36 })
37 }
38}
2

基准测试

基准测试用于测量代码性能,函数以 Benchmark 开头。

性能基准测试

go
1package main
2
3import "testing"
4
5func BenchmarkAdd(b *testing.B) {
6 for i := 0; i < b.N; i++ {
7 Add(2, 3)
8 }
9}
10
11// 运行: go test -bench=. -benchmem
上一章:数据库操作
Easy-Go-Web3

构建 Go 后端与 Web3 的学习之路。从基础到进阶,从理论到实践,助你成为全栈区块链开发者。

学习路径

  • 知识图谱
  • Go 教程
  • Go 微服务
  • 面试手册

资源中心

  • 工具箱
  • DevOps 工具
  • Web3 生态
  • 博客

© 2025 Easy-Go-Web3. All rights reserved.

Created withbyhardybao