Here is the code
a.go
package main
import "fmt"
func Haha() {
fmt.Println("in Haha")
}
func main() {
}
a_test.go
package main_test
import "testing"
func TestA(t *testing.T) {
Haha()
}
go build
works. But when I run ~/gopath/src/zjk/misc$ go test -v
. Here is what I get
# zjk/misc_test
./a_test.go:6: undefined: Haha
FAIL zjk/misc [build failed]
because you have different packages
should be:
a.go
package main
import "fmt"
func Haha() {
fmt.Println("in Haha")
}
func main() {
}
a_test.go
package main
import "testing"
func TestA(t *testing.T) {
Haha()
}
output:
# zjk/misc_test
in Haha
PASS
ok github.com/qwertmax/so 0.009s
You need to import "main"
in main_test
package & call it like main.Haha()
.
Just to elaborate why one might have the tests for a package under a different package, I should say there are two categories of tests:
One exception is package main
which is not meant to be used from inside other packages, so we just write all tests inside the package itself (as @kostya commented).
Your test is in a package called main_test
and the function is in a package called main
. You are not importing main
, so there's no way to address it.
If your test can't be in package main
, move the function to a third package.