为什么当我运行`go test`时该函数未定义?

问题描述:

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]

这是代码 p>

a.go p>

 程序包main 
 
import“ fmt” 
 
func Haha(){
 fmt.Println(“ in Haha”)
} 
 
func main(){
}  
  code>  pre> 
 
 

a_test.go p>

 包main_test 
 
导入“测试” 
 
func TestA(t  * testing.T){
 Haha()
} 
  code>  pre> 
 
 

go build code>有效。 但是当我运行〜/ gopath / src / zjk / misc $时,请测试-v code>。 这是我得到的 p>

 #zjk / misc_test 
./a_test.go:6:未定义:Haha 
FAIL zjk / misc [构建失败] 
  code  >  pre> 
  div>

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:

  • First, those tests that supervise the implementation of a package, the internals, to assure it's integrity, resource usage profile and performance benchmarks and the like. These tests should reside alongside the package code itself.
  • Second are those that test the functionality and usage of the package. In these tests, we want to assure a package stands up to it's claims about the service it provides. An important aspect of these tests is that they assure that we are not exposing any unnecessary details; to ensure private parts remain private and public API is crystal clear. That's why these tests should reside in another package, under a different name, to act as a consumer of the package under the test.

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.