diff --git a/examples/testing/main_test.go b/examples/testing/main_test.go index 3bcdd6ec..9fad09b2 100644 --- a/examples/testing/main_test.go +++ b/examples/testing/main_test.go @@ -1,11 +1,8 @@ -// Unit testing is an important part of writing -// principled Go programs. The `testing` package -// provides the tools we need to write unit tests -// and the `go test` command runs tests. +// 想要写出好的 Go 程序,单元测试是很重要的一部分。 +// `testing` 包为提供了编写单元测试所需的工具,写好单元测试后,我们可以通过 `go test` 命令运行测试。 -// For the sake of demonstration, this code is in package -// `main`, but it could be any package. Testing code -// typically lives in the same package as the code it tests. +// 为方便演示,例子的代码位于 `main` 包,实际上,单元测试的代码可以位于任何包下。 +// 测试代码通常与需要被测试的代码位于同一个包下。 package main import ( @@ -13,11 +10,9 @@ import ( "testing" ) -// We'll be testing this simple implementation of an -// integer minimum. Typically, the code we're testing -// would be in a source file named something like -// `intutils.go`, and the test file for it would then -// be named `intutils_test.go`. +// 我们要测试下面这个简单的函数——返回最小值。 +// 一般地,需要被测试的代码应该在类似于 `intutils.go` 的文件下, +// 其对应的测试文件应该被命名为 `intutils_test.go`。 func IntMin(a, b int) int { if a < b { return a @@ -26,22 +21,18 @@ func IntMin(a, b int) int { } } -// A test is created by writing a function with a name -// beginning with `Test`. +// 通常编写一个名称以 `Test` 开头的函数来创建测试。 func TestIntMinBasic(t *testing.T) { ans := IntMin(2, -2) if ans != -2 { - // `t.Error*` will report test failures but continue - // executing the test. `t.Fail*` will report test - // failures and stop the test immediately. + // `t.Error*` 会报告测试失败的信息,然后继续运行测试。 + // `t.Fail*` 会报告测试失败的信息,然后立即终止测试。 t.Errorf("IntMin(2, -2) = %d; want -2", ans) } } -// Writing tests can be repetitive, so it's idiomatic to -// use a *table-driven style*, where test inputs and -// expected outputs are listed in a table and a single loop -// walks over them and performs the test logic. +// 单元测试可以重复,所以会经常使用 *表驱动* 风格编写单元测试, +// 表中列出了输入数据,预期输出,使用循环,遍历并执行测试逻辑。 func TestIntMinTableDriven(t *testing.T) { var tests = []struct { a, b int @@ -55,9 +46,8 @@ func TestIntMinTableDriven(t *testing.T) { } for _, tt := range tests { - // t.Run enables running "subtests", one for each - // table entry. These are shown separately - // when executing `go test -v`. + // t.Run 可以运行一个 "subtests" 子测试,一个子测试对应表中一行数据。 + // 运行 `go test -v` 时,他们会分开显示。 testname := fmt.Sprintf("%d,%d", tt.a, tt.b) t.Run(testname, func(t *testing.T) { ans := IntMin(tt.a, tt.b)