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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With