Go test 可以访问生产函数,但不能访问测试函数
Go test can access production functions but not test functions
我有一个具有以下目录结构的 Go 1.14 项目:
myapp/
server/
payments/
capture_payment.go
capture_payment_test.go
billing/
billing.go
billing_test.go
fulfillment/
fulfillment.go
fulfillment_test.go
在我的 billing.go
文件中我有:
package billing
import (
"fmt"
)
func Flim() {
fmt.Println("FLIM")
}
在我的 fulfillment_test.go
文件中我有:
package fulfillment
import (
"fmt"
)
func Flam() {
fmt.Println("FLAM")
}
在我的 capture_payment_test.go
文件中我有:
package payments
import (
"testing"
"github.com/myorg/myapp/billing"
"github.com/myorg/myapp/fulfillment"
)
func TestSomething(t *testing.T) {
billing.Flim()
fulfillment.Flam()
}
当我 cd
进入 server/payments
和 运行 go test
我得到以下错误:
$ go test
# github.com/myorg/myapp/server/payments [github.com/myorg/myapp/server/payment.test]
./capture_payment_test.go:12:2: undefined: fulfillment.Flam
FAIL github.com/myorg/myapp/server/payments [build failed]
谁能发现为什么 fulfillment.Flam()
未定义,但 billing.Flim()
完全没问题?
这在 testing package 的概述中有解释:
To write a new test suite, create a file whose name ends _test.go ....
Put the file in the same package as the one being tested. The file
will be excluded from regular package builds ...
这意味着 Flam()
将不会成为 fulfillment
包的一部分,并且不能从其他包中使用。如果你想让其他包使用测试实用程序,你需要将它们放在常规 *.go
文件中而不是 *_test.go
.
我有一个具有以下目录结构的 Go 1.14 项目:
myapp/
server/
payments/
capture_payment.go
capture_payment_test.go
billing/
billing.go
billing_test.go
fulfillment/
fulfillment.go
fulfillment_test.go
在我的 billing.go
文件中我有:
package billing
import (
"fmt"
)
func Flim() {
fmt.Println("FLIM")
}
在我的 fulfillment_test.go
文件中我有:
package fulfillment
import (
"fmt"
)
func Flam() {
fmt.Println("FLAM")
}
在我的 capture_payment_test.go
文件中我有:
package payments
import (
"testing"
"github.com/myorg/myapp/billing"
"github.com/myorg/myapp/fulfillment"
)
func TestSomething(t *testing.T) {
billing.Flim()
fulfillment.Flam()
}
当我 cd
进入 server/payments
和 运行 go test
我得到以下错误:
$ go test
# github.com/myorg/myapp/server/payments [github.com/myorg/myapp/server/payment.test]
./capture_payment_test.go:12:2: undefined: fulfillment.Flam
FAIL github.com/myorg/myapp/server/payments [build failed]
谁能发现为什么 fulfillment.Flam()
未定义,但 billing.Flim()
完全没问题?
这在 testing package 的概述中有解释:
To write a new test suite, create a file whose name ends _test.go .... Put the file in the same package as the one being tested. The file will be excluded from regular package builds ...
这意味着 Flam()
将不会成为 fulfillment
包的一部分,并且不能从其他包中使用。如果你想让其他包使用测试实用程序,你需要将它们放在常规 *.go
文件中而不是 *_test.go
.