Knaph

Testing

Go ships a test runner as part of the standard toolchain — no pytest to install. A test lives in a file named *_test.go, in the same package as the code it tests:

// file: shapes/rectangle.go
package shapes
 
func Area(width, height float64) float64 {
	return width * height
}
// file: shapes/rectangle_test.go
package shapes
 
import "testing"
 
func TestArea(t *testing.T) {
	got := Area(3, 4)
	want := 12.0
 
	if got != want {
		t.Errorf("Area(3, 4) = %v, want %v", got, want)
	}
}

The conventions are all load-bearing, not stylistic preference: the file must end in _test.go, the function must start with Test, and it must take exactly one parameter, t *testing.T. Run every test in the current package with:

go test ./...

t.Errorf records a failure and lets the test function continue running (useful for reporting multiple problems from one test); t.Fatalf records a failure and stops that test function immediately — reach for it when a later assertion in the same test would panic on bad data if you tried to run it after an earlier check has already failed. There's no separate assertion library in the standard toolchain — you write the if yourself and call t.Errorf in the failing branch. This feels sparse coming from pytest or unittest's richer set of assertion helpers, but it means a Go test is just... a Go function, with no framework-specific DSL to learn beyond the one *testing.T parameter.

Table-driven tests

A pattern you'll see constantly in real Go code — one test function, many cases, via a slice of structs:

func TestArea(t *testing.T) {
	cases := []struct {
		width, height, want float64
	}{
		{3, 4, 12},
		{5, 5, 25},
		{0, 4, 0},
	}
 
	for _, c := range cases {
		got := Area(c.width, c.height)
		if got != c.want {
			t.Errorf("Area(%v, %v) = %v, want %v", c.width, c.height, got, c.want)
		}
	}
}

This is idiomatic Go doing what a pytest.mark.parametrize decorator does in Python — except it's just a slice literal and a loop, using nothing beyond what you already know.

Sign in to track your progress through this course.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.

SummarizeChatGPTClaude
Ask me questionsChatGPTClaude
Let's learn togetherChatGPTClaude