← 中文资源

简体中文版本

t.Parallel 并行执行子测试

t.Parallel 让子测试先暂停标记,等串行阶段结束后一起并行执行;把用例复制进闭包,是并行子测试共享循环变量的经典防护。

阅读英文原文

实现说明

t.Parallel 并行执行子测试可以归结为函数 shorten、TestShorten、main。 for _, tc := range cases 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 运行整个文件:main 会依次驱动 shorten。

常见问题

「t.Parallel 并行执行子测试」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

主签名形如 func TestShorten(t *testing.T)

核心语句

func shorten(s string, max int) string {
	s = strings.TrimSpace(s)
	if len(s) <= max {
		return s
	}
	return s[:max] + "…"
}
for _, tc := range cases {
	tc := tc // 复制一份用例:Go 1.22 之前循环变量共享的经典防护
	t.Run(tc.in, func(t *testing.T) {
		t.Parallel() // 标记并行:先暂停,等串行子测试跑完再一起执行
		if got := shorten(tc.in, 8); got != tc.want {
			t.Fatalf("shorten(%q) = %q, want %q", tc.in, got, tc.want)
		}
	})
}
func main() {
	// 测试用 go test -v 运行;此处演示被测逻辑本身
	fmt.Println(shorten("hello", 8))
	fmt.Println(shorten("  padded  ", 8))
	fmt.Println(shorten("long input here", 8))
}

代码示例

package main

import (
	"fmt"
	"strings"
	"testing"
)

func shorten(s string, max int) string {
	s = strings.TrimSpace(s)
	if len(s) <= max {
		return s
	}
	return s[:max] + "…"
}

func TestShorten(t *testing.T) {
	cases := []struct {
		in   string
		want string
	}{
		{"hello", "hello"},
		{"  padded  ", "padded"},
		{"long input here", "long inp…"},
	}

	for _, tc := range cases {
		tc := tc // 复制一份用例:Go 1.22 之前循环变量共享的经典防护
		t.Run(tc.in, func(t *testing.T) {
			t.Parallel() // 标记并行:先暂停,等串行子测试跑完再一起执行
			if got := shorten(tc.in, 8); got != tc.want {
				t.Fatalf("shorten(%q) = %q, want %q", tc.in, got, tc.want)
			}
		})
	}
}

func main() {
	// 测试用 go test -v 运行;此处演示被测逻辑本身
	fmt.Println(shorten("hello", 8))
	fmt.Println(shorten("  padded  ", 8))
	fmt.Println(shorten("long input here", 8))
}