在 Ubuntu 上测试 Golang(Go)代码,通常按照以下步骤进行。Go 自带了测试框架,不需要额外安装测试工具。
sudo apt update
sudo apt install golang-go
验证安装:
go version
例如创建一个项目目录:
mkdir ~/gotest
cd ~/gotest
初始化 module(Go 1.11+ 推荐):
go mod init example.com/gotest
创建文件 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)
}
}
go test
go test -v
go test ./...
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 结尾func TestXxx(t *testing.T)
cd ~/gotest
go mod init example.com/gotest
# 写 calc.go 和 calc_test.go
go test -v
如果你有 具体代码 或想测试 HTTP / 数据库 / 并发,我可以给你更具体的示例。