Go · Stage 11 – Beyond the Basics · Lesson 61 of 64

Testing with Go

Write one test using Go’s built-in testing package.

Go code

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    if got != 5 {
        t.Fatalf("got %d, want 5", got)
    }
}
Line-by-line explanation
  1. The test name begins with Test.
  2. T reports test failures.
  3. Got stores the actual result.
  4. The condition compares expected behavior.
  5. Fatalf reports a useful failure.
Expected output
PASS
ok      example.com/project

This is the expected result.

Store tests in files ending with _test.go and run them with go test ./....