TL; DR
t.Run
ã§ãã¹ããããã¹ããå®è¡ããæãRunã«æ¸¡ãé¢æ°ã¯ãããã¬ãã«ã®ãã¹ããå®è¡ããã¦ããã®ã¨å¥ã®goroutineã§å®è¡ããã¦ããã®ã§Parameterized Testãªããããã£ã¦ãå ´åãå¤æ°ã®ã¹ã³ã¼ãã«æ³¨æãã¾ãããã
詳細
Goã§ãã¹ãããã¹ãã±ã¼ã¹ãæ¸ãéã«ä»¥ä¸ã®ããã«ãã©ã¡ã¼ã¿ã¨æå¾ å¤ãæå®ãã¦forã§ãµããã¹ããå®è¡ããäºãããããã¨æãã¾ãã
import ( "fmt" "testing" ) func Add(x, y int) int { return x + y } func TestAdd(t *testing.T) { tests := []struct { x, y int expected int }{ {x: 1, y: 2, expected: 3}, {x: 2, y: 3, expected: 5}, {x: 50, y: 50, expected: 100}, } for _, tc := range tests { t.Run(fmt.Sprintf("%d+%d", tc.x, tc.y), func(t *testing.T) { if actual := Add(tc.x, tc.y); actual != tc.expected { t.Errorf("expected: %d actual: %d", tc.expected, actual) } }) } }
ãããé«éåã®ãã t.Parallel
ã追å ãã¾ãã
func TestAdd(t *testing.T) { t.Parallel() // Add tests := []struct { x, y int expected int }{ {x: 1, y: 2, expected: 3}, {x: 2, y: 3, expected: 5}, {x: 50, y: 50, expected: 100}, } for _, tc := range tests { t.Run(fmt.Sprintf("%d+%d", tc.x, tc.y), func(t *testing.T) { t.Parallel() // Add t.Logf("%+v", tc) if actual := Add(tc.x, tc.y); actual != tc.expected { t.Errorf("expected: %d actual: %d", tc.expected, actual) } }) } }
ãããå®è¡ããã¨æåãã¾ãã
ãã ãã以ä¸ã®ããã«ãã¹ãã§æ¸¡ããããã©ã¡ã¿ãåºåãã¦ã¿ãã¨ããã¹ã¦ {x:50 y:50 expected:100}
ã§ãããã¨ãåããã¾ããã¤ã¾ãæåã®ï¼ã¤ã®ãã¹ãã±ã¼ã¹ã¯æå³ããããã«åãã¦ãªãã®ã§ãã
for _, tc := range tests { t.Run(fmt.Sprintf("%d+%d", tc.x, tc.y), func(t *testing.T) { t.Parallel() t.Logf("%+v", tc) // Add if actual := Add(tc.x, tc.y); actual != tc.expected { t.Errorf("expected: %d actual: %d", tc.expected, actual) } }) }
åå ã¨å¯¾å¿
ãªãããããäºãèµ·ãããã¨ããã¨ãt.Runã«æ¸¡ãããfunctionã¯å¥ã®Goroutineã§å®è¡ããã t.Parallel
ãã¤ãããã¨ã§åãã¹ãé¢æ°ã並åã«å®è¡ããããããforæã®ã¹ã³ã¼ãã§åæåããã¦ãã tc
ã®å¤ã¯æå¾ã«ä»£å
¥ããã {x:50 y:50 expected:100}
ã®å¤ããã¹ã¦ã®functionãåç
§ãã¦ãã¾ããã¨ã«ãªãããã§ãã
ãããä¿®æ£ããããã«ã¯foræã®ä¸ã§ããä¸åº¦ tc
ãããã°OKã§ãã
for _, tc := range tests { tc := tc // Add t.Run(fmt.Sprintf("%d+%d", tc.x, tc.y), func(t *testing.T) { t.Parallel() t.Logf("%+v", tc) if actual := Add(tc.x, tc.y); actual != tc.expected { t.Errorf("expected: %d actual: %d", tc.expected, actual) } }) }
foræã®ä¸ã§ç´æ¥goroutineãdeferãå®è¡ããã¨ãã¯IDEã®IntelliJã注æãã¦ãããã®ã§æèã§ãã¦ãã®ã§ããããã¹ãã«é¢ãã¦ã¯å®å ¨ã«ç²ç¹ã§1æéã»ã©æéã溶ããã¦ãã¾ãã¾ãã..orz
åè
Frequently Asked Questions (FAQ) - The Go Programming Language