It is often useful to run a subset of the tests in a Go project. You might do this because you only want to see test results for one package or to run tests faster.

For these examples, assume your project is a Go module named examplemodule. It has the following structure:

examplemodule
    |_ go.mod
    |_ go.sum
    |_ internal
        |_ foo
        |   |_ foo.go
        |   |_ foo_test.go
        |_ bar
            |_ bar.go
            |_ bar_test.go

Here’s the most useful techniques I use to do this:

  • Run all tests: go test ./...
  • Run all tests in a package: go test examplemodule/internal/foo
  • Run a set of tests in a package: go test examplemodule/internal/foo -run TestFoo/
  • Run a single test in a package: go test examplemodule/internal/foo -run TestFoo/test_that_func_returns_expected_value

Tip: Use -v with any of the above commands to see the full names of tests.

The parameter to -run is a regular expression. So if you want to get complicated, you can do things like go test examplemodule/internal/foo -run TestFoo/test.+value to target tests whose names match the regex. In practice, I rarely do this, but it’s important to know this in case you get unexpected results when using it.