温馨提示×

ubuntu如何测试golang代码

小樊
45
2026-10-28 09:08:50
栏目: 编程语言

在 Ubuntu 上测试 Golang(Go)代码,通常按照以下步骤进行。Go 自带了测试框架,不需要额外安装测试工具。


一、安装 Go(如果还没装)

sudo apt update
sudo apt install golang-go

验证安装:

go version

二、准备 Go 项目

例如创建一个项目目录:

mkdir ~/gotest
cd ~/gotest

初始化 module(Go 1.11+ 推荐):

go mod init example.com/gotest

三、写一段 Go 代码

创建文件 calc.go:

package calc

func Add(a int, b int) int {
    return a + b
}

四、写测试代码(非常重要)

测试文件命名规则:xxx_test.go

创建 calc_test.go:

package calc

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Add(2,3) = %d; want 5", result)
    }
}

五、运行测试

1️⃣ 测试当前包

go test

2️⃣ 显示详细日志

go test -v

3️⃣ 测试所有包

go test ./...

4️⃣ 覆盖率测试

go test -cover

生成覆盖率文件:

go test -coverprofile=coverage.out
go tool cover -html=coverage.out

六、常见问题

❌ go: command not found

说明 Go 没装好或 PATH 没配置。

which go

如果没有输出,重装或手动配置 PATH。


❌ 测试文件不生效

确保:

  • 文件名以 _test.go 结尾
  • 函数和文件在同一 package
  • 测试函数格式为:
    func TestXxx(t *testing.T)
    

七、示例完整流程

cd ~/gotest
go mod init example.com/gotest
# 写 calc.go 和 calc_test.go
go test -v

如果你有 具体代码 或想测试 HTTP / 数据库 / 并发,我可以给你更具体的示例。

0 踩