oop*_*ode 3 testing internal go
假设我在包中有一个MyType
带私有方法的类型.我还有一个目录,我想在那里存储我的包的测试.这是看起来像:(mt *MyType) private()
mypackage
tests
tests/mypackage_test.go
package mypackage_test
import (
"testing"
"myproj/mypackage"
)
func TestPrivate(t *testing.T) {
// Some test code
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行时,go test
我得到了cannot refer to unexported field or method my package.(*MyType)."".private)
错误.我已经google了一下,发现从小写开始的函数不能在他们自己的包之外看到(这似乎是真的,因为大写函数可以从测试中自由调用).
我还读到了某个地方,添加<...>_internal_test.go
到测试文件可以解决我的问题,如this(tests/mypackage_internal_test.go
):
package mypackage
import (
"testing"
)
func TestPrivate(t *testing.T) {
mt := &MyType{}
// Some test code
}
Run Code Online (Sandbox Code Playgroud)
但有了这个,我才得到undefined: MyType
.所以,我的问题是:我如何测试内部/私有方法?
为什么要将测试放在不同的包中?go测试机制_test
用作测试文件的后缀,因此您可以将测试放在与实际代码相同的包中,从而避免您描述的问题.将测试放在单独的包中并不是Go中的惯用语.不要试图与Go公约作斗争,这不值得努力,你大部分都会放松战斗.