Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export data from a test package and use them in another test package in go

Tags:

go

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.

like image 305
mns Avatar asked Oct 19 '25 18:10

mns


1 Answers

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

like image 176
JimB Avatar answered Oct 22 '25 10:10

JimB