🎓 A1Learner
🔍
0 of 28 lessons completed

Go Unit Tests

A unit test is a small function that checks one piece of code and reports whether it works. Test files sit beside the code they test and run with the go test command.

A passing test

This test file sits beside the code it tests. It runs with the go test command, never with go run. TestAdd checks that Add gives 5 for 2 and 3.

package main

import "testing"

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

A failing test

TestAddWrong asks for 6 from 2 and 3 on purpose. The message line names the file, the line, and the wrong result.

package main

import "testing"

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

Errorf keeps the test going

Both checks in TestAddChecks ask for a wrong total. Errorf reports the first failure and the test still runs the second check.

package main

import "testing"

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

Example

package main

import "testing"

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

func TestMultiply(t *testing.T) {
	got := Multiply(3, 4)
	if got != 12 {
		t.Errorf("Multiply(3, 4) = %d, want 12", got)
	}
}

Key points

  • A unit test checks one small piece of code at a time.
  • A test file name ends in _test.go.
  • A test function starts with Test and takes one *testing.T value.
  • The go test command runs every test in the package.
  • A test calls Errorf with a message when a result is wrong.
  • Errorf marks the test as failed and the test keeps running.

In this example, one test file holds two tests. TestAdd checks the Add function and TestMultiply checks the Multiply function. The go test command runs both tests in file order. Each test prints its own RUN and PASS lines, and the final PASS line shows the whole file passed.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Go Playground

Exercise

How does a test report that a result is wrong?