t.Parallel Runs Subtests Concurrently

t.Parallel marks subtests to pause and run concurrently after serial setup, while copying each case into the closure keeps shared loop state per-test.

GoData Integrity

Code

gosnippet
43 lines
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))
}

Reading the code

t.Parallel Runs Subtests Concurrently keeps everything in the functions shorten, TestShorten and main.

for _, tc := range cases is the loop doing the per-item work.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func TestShorten(t *testing.T)

main sequences shorten; executing the file runs that flow once.

Core lines

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))
}

Interactive Tools for This Topic

FAQ

How do you run t.Parallel Runs Subtests Concurrently?
Just run the file; everything it needs ships with the runtime itself.