Skip to main content

What Is a Unit Test

A unit test is a small program that checks one piece of your code — usually one function. You run the tests after every change; if a change breaks something, a test tells you right away, before your users do.

Go ships everything you need: the testing package and the go test command are part of the language toolchain. No extra library to install, no setup — just a file next to your code.

Tests also make change safe: with good tests you can rewrite a function and know in seconds whether it still behaves the same.


Test Files and Test Functions

Two naming rules make a test a test:

1. The file name ends in _test.go — for calc.go you write calc_test.go. Files like this are only compiled by go test, never into your normal build.
2. The function is called TestXxx — it starts with Test, a capital letter follows, and it takes one argument: t *testing.T.

Inside the test you call the function, compare what you got with what you want, and report a failure through t when they differ. No failure reported means the test passes.

A first passing test

TestAdd calls Add(2, 3) and compares the result with 5. They match, so nothing is reported and the test passes: go test prints PASS.

Prompt
Write a Go test file with an Add function that adds two ints, and a TestAdd function that checks Add(2, 3) equals 5 using t.Errorf with a got/want message when it does not. Show the go test -v output of the passing run.
Output: Go test file and captured go test output
A first passing test

A failing test

This Add has a bug — it multiplies. The test catches it: t.Errorf prints the message with the got and want values, and the run ends with FAIL.

Prompt
Write a Go test file where the Add function has a bug (it multiplies instead of adding) and a TestAdd that expects Add(2, 3) to be 5. Show the go test -v output of the failing run with the error message.
Output: Go test file and captured go test output

Running Tests

go test runs every test in the current folder. It is quiet on success — one ok line — and talks only when something fails.

go test -v (verbose) lists every test by name with === RUN and --- PASS lines. Use it to see what actually ran. For a whole project, go test ./... runs the tests in every folder.

Two tests, verbose output

The file has two test functions, one per function under test. With -v, each shows up separately in the output — you can see both ran and both passed.

Prompt
Write a Go test file with two small functions, Double and Half, and one test function for each. Show the go test -v output where both tests appear by name and pass.
Output: Go test file and captured go test output