英文:
Static files in tests
问题
当我在Go中编写需要静态文件的测试时(例如一个名为hello.txt
的文件,在测试我的程序时,我要确保hello.txt
被正确读取),我应该把静态文件放在哪里?在测试文件中应该如何引用它们?
也就是说,目前我的设置是一个本地目录,GOPATH
设置为该目录。在这里我有:
src/
mypkg/
myfile.go
myfile_test.go
testfiles/
hello.txt
world.txt
现在在myfile_test.go
中,我不想使用绝对路径来引用testfiles/hello.txt
。有没有一种惯用的方法来做到这一点?
这种布局合理吗?
英文:
When I write tests in Go that require static files (for example a file hello.txt
where I test my program that hello.txt
is read correctly), where should I place the static files? How should I address them in the test file?
That is, currently my setup is a local directory, GOPATH
is set to this directory. There I have
src/
mypkg/
myfile.go
myfile_test.go
testfiles/
hello.txt
world.txt
Now in myfile_test.go
, I don't want to use an absolute path to refer to testfiles/hello.txt
. Is there any idiomatic way to do that?
Is this a sensible layout?
答案1
得分: 9
常见的做法是将测试文件放在与源代码文件相同的目录下,例如:
$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")
....
测试包会确保在测试二进制文件执行时,当前工作目录是 $GOPATH/src/mypkg
。
英文:
Common approach is to have, for example
$GOPATH/src/
mypkg/
myfile.go
myfile_test.go
_testdata/
hello.txt
world.txt
Then, in your foo_test, use
f, err := os.Open("_testdata/hello.txt")
....
or
b, err := ioutil.ReadFile("_testdata/hello.txt")
....
The testing package makes sure that the CWD is $GOPATH/src/mypkg
when the test binary executes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论