I'm creating some vars in B_test.go
and I want to use those same vars in A_test.go
. Can this be done in Go? I think the question boils down to whether I can export functions from B_test.go
during go test
only.
Example:
In package A_test.go
package A
var from_B = B.ExportedVars()
In package B_test.go
package B
ExportedVars() []int {
return []int{0, 1)
}
Running go test
gives
undefined B.ExportedVars
Putting ExportedVars()
in B.go
instead of B_test.go
solves the problem but this is not what I want. I want it to live in the test file.
Packages cannot see exported symbols from other package's test files, because the go
tools do not build those files into the installed package. One option you do have is to use build constraints.
Create a file or files that contain everything you want to export for whatever reason, without using the _test.go
suffix. Then mark them for build only when using your chosen tag.
// +build export
package normal
var ExportedName = somethingInternal
When testing a package dependent on this ExportedName
in package normal
, you will need to add the -tags export
flag to the test run.
This is also useful for various other reasons, like having a -tags debug
build, which can add extra functionality such as importing net/http/pprof
or expvar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With