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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run t.Parallel Runs Subtests Concurrently?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.