Testing Go Packages with Subdirectories
In the realm of Go development, a common question arises: Can we organize our tests within subdirectories to enhance workspace cleanliness? This article aims to shed light on this topic.
Testing Practices and Go Conventions
Traditionally, Go documentation recommends placing testing code in the same location as the production code. While it may simplify access to unexported program members, this approach can result in cluttered workspace. However, there is a way to separate tests into subdirectories while maintaining accessibility.
Running Tests Recursively
To execute tests across multiple subdirectories, you can leverage the "go test" command with the "./..." notation. From the project's root directory, type the following:
go test ./...
This command will recursively traverse the project's directory structure, identifying and running all test files it encounters.
Separate Directory Considerations
If tests reside in separate directories, they require extra attention. Ensure that exported variables and functions within the main package are prefixed with the package name. This allows the test files to access the exported content. Additionally, non-exported content will remain inaccessible.
Package vs. Directory Separation
While directory separation allows for cleaner organization, keeping the test file adjacent to the main source file remains a practical choice for easy file location.
Code Coverage over Time
To generate aggregate code coverage statistics for Go projects within CI/CD pipelines, utilize the "gocoverstats" project.
Integration Test Coverage
As of Go 1.20, coverage tooling now extends to integration tests, enabling the collection of profiles from larger test suites.
Alternative Testing Approach
Alternatively, you can consider organizing tests within separate packages rather than subdirectories. Test files for a package "foo" can reside in a package named "foo_test" while still remaining within the same directory. This approach prevents access to unexported members of package "foo."
The above is the detailed content of Can We Organize Go Tests in Subdirectories?. For more information, please follow other related articles on the PHP Chinese website!