Contents

Every Go test framework that supports suites needs to solve the same problem: how do you connect a struct full of test methods to the go test runner? The runner only knows about top-level func Test*(t *testing.T) functions. Your suite is a struct with methods. Something has to bridge the gap.

Most frameworks use reflection. gotest uses code generation. This post explains why, and what the code generation pipeline actually does.

The reflection approach

In a reflection-based framework like testify/suite, the bridge looks like this:

func TestUserSuite(t *testing.T) {
    suite.Run(t, new(UserSuite))
}

You write a func Test* that the runner can find, and inside it you call suite.Run, which uses the reflect package to:

  1. Enumerate all methods on UserSuite
  2. Filter for methods starting with Test
  3. Call each one as a subtest via t.Run
  4. Look for SetupTest, TearDownTest, etc. and call them at the right time

This works. But it has costs:

The code generation approach

gotest takes a different path. Instead of discovering tests at runtime with reflection, it discovers them at build time by reading your source code’s AST (abstract syntax tree). Then it generates the bridge code that a developer would otherwise write by hand.

The pipeline has three stages:

AST discovery → code generation → overlay injection

Stage 1: AST discovery

gotest loads your packages with golang.org/x/tools/go/packages and walks the syntax trees using Go’s go/ast and go/types packages. It looks for naming conventions:

This is purely static analysis. No code runs. No reflect import. The AST walker reads struct declarations and method signatures from the parse tree, the same way a linter would.

The key advantage: errors are caught before your tests run. If a lifecycle method has the wrong signature, say BeforeEach() with no parameters instead of BeforeEach(t *gotest.T), gotest reports the error at generation time with the file and line number, not as a silent no-op at runtime.

Stage 2: Code generation

From the AST analysis, gotest generates a gotest_psuite_test.go file for each package that contains suites. Here’s what gets generated for a simple suite:

your code
type UserServiceTestSuite struct {
    svc *UserService
}

func (s *UserServiceTestSuite) BeforeEach(t *gotest.T) {
    s.svc = NewUserService()
}

func (s *UserServiceTestSuite) TestCreate(t *gotest.T) { /* ... */ }
func (s *UserServiceTestSuite) TestDelete(t *gotest.T) { /* ... */ }
generated bridge (simplified)
func TestUserServiceTestSuite(t *testing.T) {
    s := &UserServiceTestSuite{}
    cfg, budget := gotestruntime.OpenSuite(t, gotestruntime.Suite{})

    gotestruntime.RunMethods(t, cfg, budget, gotestruntime.Methods{
        Cases: []gotestruntime.Method{
            {Name: "TestCreate", Run: func(it *gotest.T, run func(func())) {
                s.BeforeEach(it)
                run(func() { s.TestCreate(it) })
            }},
            {Name: "TestDelete", Run: func(it *gotest.T, run func(func())) {
                s.BeforeEach(it)
                run(func() { s.TestDelete(it) })
            }},
        },
    })
}

The generated code is a top-level func Test* that creates the struct and lists each test method with its hooks as plain function values. The gotestruntime package it calls runs each one as a subtest, in the order the lifecycle promises, and holds the timeouts.

For suites with fixtures, the generated test function also sets the fixtures up in dependency (DAG) order before the suite starts, and registers their teardown with t.Cleanup, so it runs after the suite’s AfterAll.

Stage 3: Overlay injection

Here’s the part that makes code generation practical: the generated files never touch your source tree.

Go 1.16 introduced the -overlay flag for the go toolchain. It takes a JSON file that maps virtual file paths to actual file paths on disk. When the compiler encounters a file reference, it checks the overlay map first. This means a file can appear to exist at pkg/user/gotest_psuite_test.go while actually living in the run’s own work dir.

overlay.json
{
  "Replace": {
    "/home/you/project/pkg/user/gotest_psuite_test.go": "/tmp/gotest-work-1234/overlay/0/gotest_psuite_test.go",
    "/home/you/project/pkg/order/gotest_psuite_test.go": "/tmp/gotest-work-1234/overlay/1/gotest_psuite_test.go"
  }
}

gotest writes the generated files into the run’s work dir, creates the overlay JSON, and passes it to go test -overlay=.... Nothing is ever written into your project. Your source directory stays clean, your git status stays unchanged, and pull requests don’t include generated code.

Each run writes its own overlay, so two runs never share one. Compile reuse comes from Go’s own build cache, which keys each compiled package by its files’ names and contents, not by where an overlay keeps them.

What code generation gains over reflection

The code generation approach has several concrete advantages over reflection:

Compile-time errors

If your BeforeEach method takes (ctx context.Context) instead of (t *gotest.T), gotest tells you at generation time:

user_test.go:12: unsupported param type for signature of "UserServiceTestSuite.BeforeEach": must be *gotest.T or *testing.T

With reflection, this would either panic at runtime or, worse, silently skip the hook because the framework doesn’t recognize the method signature.

Inspectable output

You can run gotest generate ./... to write the generated files to disk and read them. The generated code is standard Go; you can set breakpoints in it, step through the lifecycle logic, and see exactly what gets called in what order. The runtime it calls is ordinary Go in pkg/gotestruntime, which you can step into as well.

No registration ceremony

With reflection-based frameworks, every suite needs a top-level func Test* that calls suite.Run. With code generation, the bridge function is generated automatically. You write the suite struct and its methods, and that’s it.

reflection-based (every suite needs this)
func TestUserSuite(t *testing.T) {
    suite.Run(t, new(UserSuite))
}
code generation (nothing to write)
// The bridge is generated. Just write your suite.

Zero runtime overhead

The generated code compiles to direct function calls. No reflect.ValueOf, no reflect.Method. At test execution time, your suite methods are called directly — there is no reflective dispatch between the test runner and your code.

The pipeline in practice

When you run gotest ./..., the full pipeline executes automatically:

  1. Load packages: discover which packages match the pattern
  2. AST discovery: walk source files for suites, fixtures, lifecycle hooks
  3. Validate: check method signatures, fixture consistency, dependency cycles
  4. Generate: produce bridge code for each package
  5. Write: write generated files into the run’s work dir
  6. Overlay: create the overlay JSON mapping
  7. Compile & run: invoke go test -overlay=...

Steps 1–6 are fast; they operate on parse trees, not compiled code. And repeat runs stay cheap: Go’s build cache keys the overlaid files by their content, so an unchanged source hits it wherever the overlay lives.

For large projects, gotest also uses streaming compilation: test packages start running as soon as they’re compiled, without waiting for all packages to finish compiling. This overlaps compilation time with execution time, reducing wall-clock duration for multi-package test runs — the place this matters most is CI, as covered in Go Tests in GitHub Actions.

Inspecting the generated code

If you’re curious about what gotest generates for your project, you can write the files to disk:

# Write generated files alongside your source
gotest generate ./...

# Look at what was generated
cat pkg/user/gotest_psuite_test.go

# Clean up when done
gotest clean ./...

The generated files are standard Go test files. They import your package, reference your types, and call your methods. Reading them shows which of your methods the framework calls and in what order; the calls themselves are made by pkg/gotestruntime. If you’d rather start from the other end — write a small suite and then inspect what gets generated for it — Your First Go Test Suite in 10 Minutes walks through exactly that.

The trade-off

Code generation isn’t free. It adds a build step: the AST discovery and generation that runs before go test. And plain go test has no idea your suites exist — without the generated bridge, the package compiles cleanly and simply reports no tests. Your suites are structs with methods; nothing runs them until the bridge does.

If part of your workflow has to invoke go test directly, run gotest generate ./... first to materialize the bridge files on disk, and gotest clean ./... to remove them afterwards.

Day to day, the build step mostly disappears: generation operates on parse trees, Go’s build cache recompiles only the packages whose files changed, and an unchanged test binary is not linked again, so the edit-test loop stays close to plain go test. Go Test Watch Mode and Focused Tests covers what that loop looks like in practice.

The code generation approach aligns with Go’s broader philosophy: explicit over implicit, compile-time over runtime, readable code over framework magic. The generated code lists your hooks and methods as plain function values, and an ordinary Go package runs them. gotest just writes the list for you.

Run gotest generate on your own suite and read the bridge it writes.

go get -tool github.com/mvrahden/go-test/cmd/gotest@latest