测试中的静态文件

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2013年8月26日 00:38:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/18431232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定