skip to content
Alvin Lucillo

Go test race condition

/ 1 min read

💻 Tech

Go test can check for race condition by adding the -race flag.

The code below demonstrates a race condition because two goroutines read and write to the counter variable concurrently without synchronization.

main.go

var counter int

func increment(wg *sync.WaitGroup) {
	defer wg.Done()
	counter++
}

main_test.go

func TestIncrement(t *testing.T) {
	var wg sync.WaitGroup

	wg.Add(1)
	go increment(&wg)
	go increment(&wg)

	wg.Wait()
}

To run the test: go test -v -race .

Sample output:

=== RUN   TestIncrement
--- PASS: TestIncrement (0.00s)
==================
WARNING: DATA RACE
Read at 0x00000077f368 by goroutine 8: