This question already has an answer here:
I have a db package. Inside of a db_test.go I define a MemoryDb() function to return an in memory database for testing purposes. I can use MemoryDb() from my db_test.go just fine, but I would also like to use it in some other package, apkg's apkg_test.go. That doesn't seem to work, should it?
apkg_test.go
package apkg
import (
"db"
"testing"
)
func TestHelloWorld(t *testing.T) {
_ = db.MemoryDb()
}
db.go
package db
// Db struct
type Db struct {
}
db_test.go
package db
import "testing"
func TestHelloWorld(t *testing.T) {
_ = MemoryDb()
}
func MemoryDb() Db {
return Db{}
}
Error that I get
/tmp/go/src/db$ go test
PASS
ok db 0.008s
/tmp/go/src/db$ cd ../apkg/
/tmp/go/src/apkg$ go test
$ apkg [apkg.test]
./apkg_test.go:9:6: undefined: db.MemoryDb
FAIL apkg [build failed]
Assuming this is not allowed because it's in a _test in another package, is there any way to reach into another package's _test files from other _test files in other packages? I'd rather factor out the MemoryDb but still keep separate _test.go files in separate packages and keey MemoryDb out of deployed binaries (keep it in a _test.go file).
</div>