当我在 Go 中编写需要静态文件的测试时(例如文件 hello.txt
我测试我的程序 hello.txt
被正确读取),其中我应该放置静态文件吗?我应该如何在测试文件中解决它们?
也就是说,目前我的设置是一个本地目录,GOPATH
设置为这个目录。我有
src/
mypkg/
myfile.go
myfile_test.go
testfiles/
hello.txt
world.txt
现在在 myfile_test.go
中,我不想使用绝对路径来引用 testfiles/hello.txt
。有什么惯用的方法可以做到这一点吗?
这是一个合理的布局吗?
最佳答案
常用的做法是有,例如</p>
$GOPATH/src/
mypkg/
myfile.go
myfile_test.go
_testdata/
hello.txt
world.txt
然后,在您的 foo_test 中,使用
f, err := os.Open("_testdata/hello.txt")
....
或
b, err := ioutil.ReadFile("_testdata/hello.txt")
....
测试包确保在执行测试二进制文件时 CWD 是 $GOPATH/src/mypkg
。
关于testing - 测试中的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18431232/