The go test command in Go provides a flexible test case mechanism, including: naming rules: Test
In Go, testing using the go test
command ensures Code correctness and reliability. Its power comes from a flexible and extensible test case mechanism.
The naming rules of test case functions follow the following format: Test<Function or module name>
. Each test case function must have a *testing.T
type parameter that reports test status and other information.
import "testing" func TestAdd(t *testing.T) { // ... 测试代码 }
Assertion is a function used to verify whether the expected value and the actual value are consistent. Go's test package provides several assertion functions, such as:
t.Equal(a, b)
: Verify that a is equal to bt .NotEqual(a, b)
: Verify that a is not equal to bt.True(x)
: Verify that x is truet.False (x)
: Verify that x is falset.Error(err)
: Verify that err is not nilSubtests allow large test cases to be broken down into smaller, manageable parts. Create a subtest using the t.Run()
function, passing the subtest name and a test function.
func TestMath(t *testing.T) { t.Run("add", func(t *testing.T) { // 测试加法的子测试 }) t.Run("subtract", func(t *testing.T) { // 测试减法的子测试 }) }
Tabular testing allows you to run a set of test cases using tabular data. Use the t.RunTable()
function to create a table test, passing the table data and a test function.
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) }
The following is an example of using go test
to test Web services:
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
is a powerful tool that allows you to create and manage various test cases. Taking full advantage of the power of assertions, subtests, and table tests, you can write comprehensive and reliable tests, improving the quality and reliability of your code.
The above is the detailed content of Explore the mysteries of test cases using go test. For more information, please follow other related articles on the PHP Chinese website!