go / beginner
Snippet
Writing Basic Tests in Go
Go has built-in testing support through the testing package. Test files are named with _test.go suffix. Test functions start with Test prefix and receive a *testing.T argument. The t.Errorf() method marks a test as failed while allowing execution to continue. Use t.Run() for subtests to organize related test cases cleanly.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package mainimport "testing"func Add(a, b int) int {return a + b}func TestAdd(t *testing.T) {result := Add(2, 3)expected := 5if result != expected {t.Errorf("Add(2, 3) = %d, expected %d", result, expected)}}func TestAddNegative(t *testing.T) {result := Add(-5, 3)expected := -2if result != expected {t.Errorf("Add(-5, 3) = %d, expected %d", result, expected)}}
Breakdown
1
func TestAdd(t *testing.T)
Test function receives testing.T parameter - t parameter controls test execution
2
t.Errorf("...", result, expected)
Errorf logs failure message without stopping test execution
3
t.Run("subtest name", func(t *testing.T) { })
Subtests using t.Run() group related test cases with descriptive names
4
testing.T
Testing.T type provides methods for logging and controlling test flow