Home >Backend Development >Golang >How to Achieve Test Coverage for Code Separated from Tests in Go?
Testing Coverage for Code Separated from Tests
Despite the advantage of organizing test files separately for a cleaner codebase and limiting tests to public API interactions, it poses a challenge in obtaining coverage for the target package under test (in this case, api_client).
To address this issue, we can leverage the -coverpkg flag along with the package name when running tests:
go test -cover -coverpkg "api_client" "api_client_tests"
This command will run the tests with coverage enabled for the api_client package.
While separating test files from code files is permissible, it's important to note that it deviates from Go's standard approach. This means that package-private variables or functions will not be accessible by tests outside of the package, even if they are in separate directories.
To enforce black-box testing, where tests should only access public API methods, you can still keep tests in separate packages without physically moving the files. For example:
<code class="go">// api_client.go package api_client // Private variable not accessible outside package var privateVar = 10 func PublicMethod() {}</code>
<code class="go">// api_client_test.go package api_client_tests import ( "testing" "api_client" // Import api_client package ) func TestPublicMethod(t *testing.T) { api_client.PublicMethod() }</code>
In this example, the privateVar and Method function from api_client.go are inaccessible to the test file, ensuring that tests interact only via the public API.
The above is the detailed content of How to Achieve Test Coverage for Code Separated from Tests in Go?. For more information, please follow other related articles on the PHP Chinese website!