Go Unit Testing Explained for Beginners

Updated 5 min read
Go Unit Testing featured image: cards showing a test function, go test and coverage

Go unit testing is built right into the language, so you can check your code without installing any extra tools. In this post, you will write your first test, use table-driven tests, measure coverage and run benchmarks. Each idea comes with a short example that you can run yourself.

Tests live inside packages, so first make sure you understand modules and packages in Go. We will also test a function that returns an error, which you learned in error handling in Go for beginners.

What Is Go Unit Testing?

A unit test is a small piece of code that checks one function gives the right answer. If someone changes that function later and breaks it, the test fails and warns you. So tests act as a safety net for every future change.

Think of a car’s dashboard warning lights. You do not inspect the engine every morning. Instead, the lights tell you the moment something goes wrong. Similarly, Go unit testing tells you right away when your code breaks.

Your First Test

// mathx/mathx.go
package mathx

func Add(a, b int) int {
	return a + b
}
// mathx/mathx_test.go
package mathx

import "testing"

func TestAdd(t *testing.T) {
	got := Add(2, 3)
	want := 5
	if got != want {
		t.Errorf("Add(2, 3) = %d, want %d", got, want)
	}
}

The test calls the function, then compares what it got with what you want. If they differ, t.Errorf marks the test as failed and prints a clear message.

The Rules for Test Files

  • The file name must end in _test.go.
  • Each test function starts with Test and a capital letter.
  • It takes one parameter: t *testing.T.

Running Tests with go test

go test ./...
# ok   example.com/mathx/mathx   0.002s

The ./... pattern runs tests in every package of your module. Also, add -v to see each test name as it runs.

What a Failing Test Looks Like

--- FAIL: TestAdd (0.00s)
    mathx_test.go:9: Add(2, 3) = 5, want 6
FAIL

Here we changed want to 6 on purpose. Go shows the test name, the file, the line number and your message. As a result, you can jump straight to the problem.

Table-Driven Tests in Go Unit Testing

func TestAddTable(t *testing.T) {
	tests := []struct {
		name string
		a, b int
		want int
	}{
		{"positive", 2, 3, 5},
		{"zero", 0, 0, 0},
		{"negative", -2, -3, -5},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := Add(tt.a, tt.b); got != tt.want {
				t.Errorf("got %d, want %d", got, tt.want)
			}
		})
	}
}

Instead of writing one test per case, you list all cases in a table. Then a loop runs each row as a subtest with t.Run. This is the most popular style in Go projects, as the diagram shows.

Go Unit Testing diagram showing a table of test cases running as named subtests

Each row in the table becomes its own named subtest, so you see exactly which case passed or failed.

t.Errorf vs t.Fatal

func TestDivideByZero(t *testing.T) {
	_, err := Divide(10, 0)
	if err == nil {
		t.Fatal("expected an error, got nil")
	}
}

t.Errorf records a failure but keeps running the test. In contrast, t.Fatal stops the test at once. So use Fatal when the rest of the test makes no sense after the failure.

Measuring Go Unit Testing Coverage

go test -cover ./mathx
# ok   example.com/mathx/mathx   0.003s   coverage: 75.0% of statements

Coverage shows how much of your code the tests actually run, which is a key Go unit testing metric. Here the success path of Divide has no test yet, so we are at 75%. Aim for the important paths rather than a perfect 100%.

Benchmarks

func BenchmarkAdd(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Add(2, 3)
	}
}

// go test -bench=. ./mathx
// BenchmarkAdd-2   1000000000   0.3233 ns/op

A benchmark measures speed. Go runs the loop many times and reports the average time per call. Your numbers will differ, because they depend on your machine.

Go Unit Testing Best Practices

  • Write clear failure messages with both got and want.
  • Use table-driven tests for many similar cases.
  • Test error paths, not only the happy path.
  • Run go test -race in your build pipeline.

Common Mistakes in Go Unit Testing

Output you seeWhy it happensHow to fix it
[no test files]The file is not named *_test.go.Rename it, for example mathx_test.go.
[no tests to run]The function starts with lowercase test.Rename it to TestAdd.
Test passes but code is wrongThe test never checks the result.Compare got with want.

The first two give no error at all, which makes them easy to miss. Testing questions also come up in my Go interview questions and answers, so give them a try.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go unit testing needs only the testing package and go test.
  • Test files end in _test.go, and test names start with Test.
  • Table-driven tests with t.Run handle many cases cleanly.
  • Errorf keeps going, while Fatal stops the test.
  • Use -cover for coverage and -bench for speed.

What’s Next?

Now you can prove your code works. Next, we will turn Go structs into JSON and back, which every backend developer does daily.

Coming soon: Go JSON Encoding and Decoding Explained