[go] How to run test cases in a specified file?

My package test cases are scattered across multiple files, if I run go test <package_name> it runs all test cases in the package.

It is unnecessary to run all of them though. Is there a way to specify a file for go test to run, so that it only runs test cases defined in the file?

This question is related to go

The answer is


in intelliJ IDEA go-lang plugin (and i assume in jetbrains Gogland) you can just set the test kind to file under run > edit configurations

screenshot create go test on go file


go test -v ./<package_name> -run Test

Prevents caching of test results.

go test -count=1 ./<package_name> -run Test

go test -v -timeout 30s <path_to_package> -run ^(TestFuncRegEx)
  • The TestFunc must be inside a go test file in that package
  • We can provide a regular expression to match a set of test cases or just the exact test case function to run a single test case. For instance -run TestCaseFunc

alias testcases="sed -n 's/func.*\(Test.*\)(.*/\1/p' | xargs | sed 's/ /|/g'"

go test -v -run $(cat coordinator_test.go | testcases)

Visual Studio Code shows a link at the top of a Go test file which lets you run all the tests in just that file.

enter image description here

In the "Output" window, you can see that it automatically generates a regex which contains all of the test names in the current file:

Running tool: C:\Go\bin\go.exe test -timeout 30s -run ^(TestFoo|TestBar|TestBaz)$ rootpackage\mypackage

Note: the very first time you open a Go file in VS Code it automatically offers to install some Go extensions for you. I assume the above requires that you have previously accepted the offer to install.


@zzzz's answer is mostly complete, but just to save others from having to dig through the referenced documentation you can run a single test in a package as follows:

go test packageName -run TestName

Note that you want to pass in the name of the test, not the file name where the test exists.

The -run flag actually accepts a regex so you could limit the test run to a class of tests. From the docs:

-run regexp
    Run only those tests and examples matching the regular
    expression.

When running a single test I usually do:

go test -run TestSomethingReallyCool ./folder1/folder2/ -v -count 1

-count 1 also ensures that the test is ran every time instead of being cached. Useful when you are testing against race conditions and have a test that fails only sometimes. In Go versions not using modules the same could be achieved by setting GOCACHE=off but this interacts poorly with Go modules.