Reusing Test Code in Imported Packages in Go
In your directory structure, you have a test utility function in pkg1_test.go that you wish to use in main_test.go, which imports pkg1. However, the function in pkg1_test.go uses an unexported function in pkg1, making it unavailable outside of the package.
Consider the following approaches:
Moving the Function to pkg1.go
While moving the function to pkg1.go would make it accessible in main_test.go, it could lead to the function being included in the binary generated by go build. This is undesirable for test-only functions.
Creating a Separate Test Utility Package
Moving the function to a separate test utility package and importing it manually in *_test.go files seems ideal. However, the function still requires access to internal methods in pkg1, which may not be exported.
A Hybrid Approach
For your specific scenario, a hybrid approach offers a solution:
In pkg1_test.go, add a function like this:
<code class="go">func getPrivateData() []byte { // Code to get internal data from pkg1 }</code>
This approach allows you to reuse your test utility function while keeping it separate from the production code and avoiding the problem of unexported functions.
The above is the detailed content of How to Reuse Test Code from Imported Packages in Go with Unexported Functions?. For more information, please follow other related articles on the PHP Chinese website!