go 中的 go test 命令提供灵活的测试用例机制,包括:命名规则:test,参数为 *testing.t断言:验证期望值和实际值是否一致,例如 t.equal() 和 t.error()子测试:分解大型测试用例为更小的部分,使用 t.run() 创建表格测试:使用表格数据运行测试用例,使用 t.runtable() 创建实战案例:演示使用 go test 测试 web 服务
利用 Go Test 探索测试用例的奥秘
在 Go 中,使用 go test
命令进行测试可以确保代码的正确性和可靠性。它的强大功能来自灵活且可扩展的测试用例机制。
测试用例的基本语法
测试用例函数的命名规则遵循以下格式: Test
。每个测试用例函数必须有一个 *testing.T
类型参数,用于报告测试状态和其他信息。
import "testing"
func TestAdd(t *testing.T) {
// ... 测试代码
}
断言
断言是用来验证期望值和实际值是否一致的函数。Go 的测试包提供了几个断言函数,比如:
t.Equal(a, b)
:验证 a 等于 bt.NotEqual(a, b)
:验证 a 不等于 bt.True(x)
:验证 x 为 truet.False(x)
:验证 x 为 falset.Error(err)
:验证 err 不为 nil
子测试
子测试允许将大型测试用例分解成较小的、可管理的部分。使用 t.Run()
函数创建子测试,传递子测试名称和一个测试函数。
func TestMath(t *testing.T) {
t.Run("add", func(t *testing.T) {
// 测试加法的子测试
})
t.Run("subtract", func(t *testing.T) {
// 测试减法的子测试
})
}
表格测试
表格测试可让您使用表格数据运行一组测试用例。使用 t.RunTable()
函数创建表格测试,传递表格数据和一个测试函数。
func TestTable(t *testing.T) {
type Input struct {
a, b int
}
tests := []Input{
{1, 2},
{3, 4},
{5, 6},
}
t.RunTable("add", func(t *testing.T, in Input) {
// 测试 add 函数,使用 in.a 和 in.b
}, tests)
}
实战案例:测试 Web 服务
下面是一个使用 go test
测试 Web 服务的示例:
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestGetProducts(t *testing.T) {
// 创建一个模拟 HTTP 请求
req, err := http.NewRequest("GET", "/api/products", nil)
if err != nil {
t.Fatal(err)
}
// 创建一个响应记录器
rr := httptest.NewRecorder()
// 调用正在测试的处理程序
http.HandlerFunc("/api/products", getProducts).ServeHTTP(rr, req)
// 验证响应的状态码
if status := rr.Code; status != http.StatusOK {
t.Errorf("错误的状态码:%d", status)
}
// 验证响应 body
expected := `{"products": [{"id": 1, "name": "Product 1"}, {"id": 2, "name": "Product 2"}]}`
if body := rr.Body.String(); body != expected {
t.Errorf("错误的响应 body:%s", body)
}
}
结语
go test
是一个强大的工具,可让您创建和管理各种测试用例。充分利用断言、子测试和表格测试的功能,您可以编写全面和可靠的测试,提高代码的质量和可靠性。