Home >Backend Development >Golang >How Can I Selectively Run Go Tests and Exclude Specific Packages or Directories?
Selective Testing: Skipping Packages in Go
When running test suites, you may encounter situations where you want to exclude certain packages or directories from testing. In Go, it's possible to specify the packages to test directly from the command line.
For example, let's say you have a project structure like this:
mypackage mypackage/net mypackage/other mypackage/scripts
To test only the mypackage, mypackage/other, and mypackage/net packages while excluding mypackage/scripts, you can use the following command:
go test import/path/to/mypackage import/path/to/mypackage/other import/path/to/mypackage/net
Alternatively, if your preferred shell syntax allows it, you can use the following shorthand:
go test import/path/to/mypackage{,/other,/net}
Another approach involves utilizing go list, which returns a list of packages matching a given pattern. You can pipe this output to a command like grep and filter out the packages you don't want to test, like so:
go test `go list ./... | grep -v directoriesToSkip`
In cases where the reason for skipping tests is to optimize runtime, the test functions themselves can check testing.Short() and decide whether to skip using t.Skip(). This allows for selective testing when calling go test -short.
The above is the detailed content of How Can I Selectively Run Go Tests and Exclude Specific Packages or Directories?. For more information, please follow other related articles on the PHP Chinese website!