Go语言单元测试需创建以_test.go结尾的文件并编写Test开头的函数,使用go test命令运行;通过t.Error、t.Fatal等方法报告结果,可结合t.Run进行子测试,用t.Helper()编写辅助断言函数,推荐将测试文件与源码同包以直接访问内部函数,同时利用接口和Mock隔离依赖,确保测试独立可重复。

在Go语言里写单元测试,核心就是利用它内置的
testing
_test
_test.go
Test
*testing.T
go test
Golang的
testing
// main.go
package main
func Add(a, b int) int {
return a + b
}
func Subtract(a, b int) int {
return a - b
}然后,在同目录下,我创建一个
main_test.go
_test.go
// main_test.go
package main // 或者 package main_test,看你的需求
import (
"testing"
)
func TestAdd(t *testing.T) {
// 预期结果和实际结果的比较
result := Add(1, 2)
expected := 3
if result != expected {
// t.Errorf 会标记测试失败,但会继续执行后续测试
t.Errorf("Add(1, 2) 期望得到 %d, 实际得到 %d", expected, result)
}
// 另一个测试用例
result = Add(-1, 1)
expected = 0
if result != expected {
t.Errorf("Add(-1, 1) 期望得到 %d, 实际得到 %d", expected, result)
}
}
func TestSubtract(t *testing.T) {
result := Subtract(5, 2)
expected := 3
if result != expected {
// t.Fatalf 会标记测试失败,并立即停止当前测试函数的执行
t.Fatalf("Subtract(5, 2) 期望得到 %d, 实际得到 %d", expected, result)
}
// 你也可以用 t.Logf 来输出一些调试信息,它只在测试失败或使用 -v 模式时显示
t.Logf("Subtract(5, 2) 测试通过,结果为 %d", result)
}
// 示例:使用 t.Run 进行子测试,让测试结构更清晰
func TestComplexOperation(t *testing.T) {
t.Run("Positive Numbers", func(t *testing.T) {
if Add(10, 5) != 15 {
t.Error("Positive numbers addition failed")
}
})
t.Run("Negative Numbers", func(t *testing.T) {
if Add(-10, -5) != -15 {
t.Error("Negative numbers addition failed")
}
})
t.Run("Zero Case", func(t *testing.T) {
if Add(0, 0) != 0 {
t.Error("Zero addition failed")
}
})
}
// 辅助函数,避免重复的断言逻辑
func assertEqual(t *testing.T, actual, expected int, msg string) {
t.Helper() // 标记为辅助函数,错误报告会指向调用它的行
if actual != expected {
t.Errorf("%s: 期望 %d, 实际 %d", msg, expected, actual)
}
}
func TestAddWithHelper(t *testing.T) {
assertEqual(t, Add(1, 2), 3, "Add(1, 2)")
assertEqual(t, Add(10, -5), 5, "Add(10, -5)")
}运行测试很简单,在命令行里,进入到你的项目根目录或者包含
main_test.go
立即学习“go语言免费学习笔记(深入)”;
go test
如果你想看更详细的输出,包括通过的测试:
go test -v
如果只想运行某个特定的测试函数,比如
TestAdd
go test -run TestAdd
testing.T
t.Error
t.Errorf
t.Fatal
t.Fatalf
t.Log
t.Logf
go test -v
t.Run
t.Helper()
t.Helper()
在Go语言里,测试文件的组织和命名其实有几种常见的做法,每种都有它的道理和适用场景。最常见的,也是Go官方推荐的,就是把测试文件和它要测试的源文件放在同一个包里,但文件名必须以
_test.go
user.go
user_test.go
这样做的好处是显而易见的:
不过,有时候你可能会看到另一种组织方式:将测试文件放在一个单独的测试包里,通常是原包名后加
_test
user
user_test
// user.go
package user
func GetUserName(id int) string {
// ...
return "TestUser"
}
// user_test/user_test.go
package user_test // 注意这里是 user_test 包
import (
"testing"
"your_module/user" // 需要导入 user 包
)
func TestGetUserName(t *testing.T) {
if user.GetUserName(1) != "TestUser" { // 只能访问导出的函数
t.Error("GetUserName failed")
}
}这种方式的优点在于:
_test
通常情况下,我倾向于将测试文件放在同一个包内。因为Go语言本身就鼓励你写小而精的函数,很多时候,一个包内的内部函数才是真正的业务逻辑核心,对外暴露的只是一个门面。如果不能直接测试这些内部函数,你可能需要写更多复杂的集成测试,或者为了测试而把内部函数导出,这无疑会污染API。当然,如果一个功能点特别复杂,或者涉及到对外API的集成测试,我可能会考虑用
_test
t.Run
测试最怕的就是不确定性。一个好的单元测试应该是独立、可重复的,它不应该依赖外部环境,也不应该产生副作用影响后续的测试。但在实际开发中,我们的代码往往会依赖数据库、网络服务、文件系统,甚至其他复杂的业务模块。处理这些依赖和副作用,是写好测试的关键。
首先,最核心的原则是隔离。你的单元测试应该只关注被测单元自身的逻辑,而不是它所依赖的外部系统。
1. 接口和Mock/Stub
这是最常见也最有效的方法。Go语言的接口(interface)在这里发挥了巨大作用。如果你的函数依赖一个外部服务,不要直接在函数内部实例化那个服务,而是让函数接受一个接口作为参数。这样,在测试时,你就可以传入一个实现了这个接口的“模拟对象”(Mock或Stub)。
比如,你的服务需要访问数据库:
// 业务代码
type UserRepository interface {
GetUserByID(id int) (User, error)
}
type UserService struct {
Repo UserRepository
}
func (s *UserService) GetUserDetails(id int) (User, error) {
// ... 业务逻辑
return s.Repo.GetUserByID(id)
}
// 测试代码
type MockUserRepository struct {
GetUserByIDFunc func(id int) (User, error)
}
func (m *MockUserRepository) GetUserByID(id int) (User, error) {
if m.GetUserByIDFunc != nil {
return m.GetUserByIDFunc(id)
}
return User{}, errors.New("not implemented") // 默认实现,如果没设置则报错
}
func TestGetUserDetails(t *testing.T) {
mockRepo := &MockUserRepository{
GetUserByIDFunc: func(id int) (User, error) {
if id == 1 {
return User{ID: 1, Name: "TestUser"}, nil
}
return User{}, errors.New("user not found")
},
}
userService := &UserService{Repo: mockRepo}
user, err := userService.GetUserDetails(1)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if user.Name != "TestUser" {
t.Errorf("Expected TestUser, got %s", user.Name)
}
_, err = userService.GetUserDetails(2)
if err == nil {
t.Error("Expected error for non-existent user, got nil")
}
}这里,我们通过
MockUserRepository
UserService
2. t.Cleanup()
在测试中,有时你不得不创建一些临时资源,比如文件、数据库连接等。
t.Cleanup()
func TestWithTempFile(t *testing.T) {
tempDir := t.TempDir() // Go 1.15+ 提供的,自动创建临时目录并注册清理函数
tempFilePath := filepath.Join(tempDir, "test.txt")
err := os.WriteFile(tempFilePath, []byte("hello"), 0644)
if err != nil {
t.Fatalf("Failed to create temp file: %v", err)
}
// t.Cleanup(func() {
// // 在 Go 1.15+ 中,t.TempDir() 已经自动处理了目录清理,
// // 所以这里通常不需要手动 os.RemoveAll(tempDir)
// // 但如果你手动创建了文件,可以用 t.Cleanup 来清理
// // t.Logf("Cleaning up temp file: %s", tempFilePath)
// // os.Remove(tempFilePath)
// })
// 假设你的函数读取这个文件
content, err := os.ReadFile(tempFilePath)
if err != nil {
t.Fatalf("Failed to read temp file: %v", err)
}
if string(content) != "hello" {
t.Errorf("Unexpected content: %s", string(content))
}
}t.TempDir()
3. httptest
如果你的代码依赖HTTP服务(比如调用RESTful API),
net/http/httptest
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func fetchContent(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func TestFetchContent(t *testing.T) {
// 创建一个测试HTTP服务器
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/test" {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello from test server!"))
} else {
w.WriteHeader(http.StatusNotFound)
}
}))
defer ts.Close() // 测试结束时关闭服务器
content, err := fetchContent(ts.URL + "/test")
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if content != "Hello from test server!" {
t.Errorf("Expected 'Hello from test server!', got '%s'", content)
}
_, err = fetchContent(ts.URL + "/nonexistent")
if err == nil {
t.Error("Expected an error for non-existent path, got nil")
}
}这些方法的核心思想都是将外部依赖“虚拟化”或“沙盒化”,让你的测试运行在一个可控、纯净的环境中。这不仅能提高测试的稳定性,还能大大加快测试的执行速度。
Go语言的
testing
unittest
if actual != expected { t.Errorf(...) }1. 原生比较和错误报告
这是最直接,也是Go官方推荐的方式。你直接用
if
t.Error
t.Errorf
t.Fatal
t.Fatalf
func TestEquality(t *testing.T) {
actual := "hello"
expected := "world"
if actual != expected {
t.Errorf("字符串不匹配:期望 %q, 实际 %q", expected, actual)
}
numActual := 10
numExpected := 20
if numActual >= numExpected { // 注意,这里故意写了个会失败的条件
t.Errorf("数字比较失败:期望 %d 小于 %d, 实际 %d", numActual, numExpected, numActual)
}
}
func TestErrorHandling(t *testing.T) {
_, err := someFunctionThatMightReturnError() // 假设这个函数返回一个错误
if err == nil {
t.Fatal("期望得到一个错误,但实际为 nil") // 遇到严重错误直接停止
}
// 检查错误类型或内容
if err.Error() != "specific error message" {
t.Errorf("期望的错误信息是 'specific error message', 实际是 '%v'", err)
}
}
func someFunctionThatMightReturnError() (int, error) {
return 0, errors.New("specific error message")
}这种方式的好处在于:
if err != nil
2. 自定义辅助函数
随着测试用例的增多,你可能会发现很多重复的
if actual != expected
t.Helper()
// assertEqual 检查两个值是否相等
func assertEqual(t *testing.T, actual, expected interface{}, msg string) {
t.Helper()
if actual != expected {
t.Errorf("%s: 期望 %v, 实际 %v", msg, expected, actual)
}
}
// assertNotEqual 检查两个值是否不相等
func assertNotEqual(t *testing.T, actual, expected interface{}, msg string) {
t.Helper()
if actual == expected {
t.Errorf("%s: 期望 %v 不等于 %v, 实际相等", msg, expected, actual)
}
}
// assertNil 检查值是否为 nil
func assertNil(t *testing.T, actual interface{}, msg string) {
t.Helper()
if actual != nil {
t.Errorf("%s: 期望 nil, 实际 %v", msg, actual)
}
}
// assertNotNil 检查值是否不为 nil
func assertNotNil(t *testing.T, actual interface{}, msg string) {
t.Helper()
if actual == nil {
t.Errorf("%s: 期望非 nil, 实际 nil", msg)
}
}
func TestMyLogic(t *testing.T) {
result := 1 + 1
assertEqual(t, result, 2, "加法结果")
err := someFunctionThatMightReturnError()
assertNotNil(t, err, "函数应该返回错误")
assertEqual(t, err.Error(), "specific error message", "错误信息匹配")
}这种方式兼顾了原生方法的清晰性,又解决了代码重复的问题。我个人非常推荐这种做法,因为它完全符合Go的风格,且易于维护。
3. 第三方断言库(可选)
虽然Go社区推崇原生方式,但也有一些第三方库提供了更丰富的断言功能,它们通常模仿其他语言的断言风格,让测试代码看起来更简洁。其中最流行的是
github.com/stretchr/testify/assert
import (
"testing"
"github.com/stretchr/testify/assert" // 导入 testify/assert
)
func TestWithTestify(t *testing.T) {
result := 1 + 1
assert.Equal(t, 2, result, "加法结果不正确") // 期望值在前,实际值在后
err := someFunctionThatMightReturnError()
assert.NotNil(t, err, "函数应该返回错误")
assert.EqualError(t, err, "specific error message", "错误信息不匹配")
// 更多断言方法,例如:
assert.True(t, result > 0, "结果应该大于零")
assert.Contains(t, "hello world", "world", "字符串应包含子串")
assert.Len(t, []int{1, 2, 3}, 3, "切片长度不正确")
}使用第三方库的优点是:
以上就是Golang单元测试怎么写 testing框架基础用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号