Write _test.go files and Test functions
Write _test.go files and Test functions
A unit test checks a small piece of behavior automatically. Put tests in files ending in _test.go; go test compiles these separately from ordinary builds. A test function is named TestXxx, where the part after Test does not begin with a lowercase letter, and has signature func TestXxx(t *testing.T). Use t.Errorf to report a mismatch or t.Fatalf to stop the current test immediately.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func Double(n int) int { return n * 2 }
--- calc_test.go ---package calc
import "testing"
func TestDouble(t *testing.T) { if got := Double(4); got != 8 { t.Errorf("Double(4) = %d; want 8", got) }}The test compares the actual value against a known expectation. The test runner reports PASS if no failure is reported. The command exits nonzero when a test fails. Do not rely on printing values alone: a printed incorrect value does not automatically fail a test.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestDoubleCheck a boundary value
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func ClampZero(n int) int { if n < 0 { return 0 } return n}
--- calc_test.go ---package calc
import "testing"
func TestClampZero(t *testing.T) { if got := ClampZero(-2); got != 0 { t.Fatalf("negative: got %d", got) } if got := ClampZero(5); got != 5 { t.Errorf("positive: got %d", got) }}Both a negative and a positive input are checked. Fatalf stops this test goroutine through FailNow; Errorf marks failure but permits further statements. Use Fatalf when subsequent checks depend on success. A passing test is evidence for its cases, not a proof of all inputs.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestClampZeroTry it locally
Implement Triple(n int) int and test 0 and -3 with expected 0 and -9. Then deliberately return n instead and observe failure. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Testing fundamentals 01: Write _test.go files and Test functions
Check the lesson objective before moving on.
Which file name is recognized as a test source?
What happens after t.Errorf?