gpt4 book ai didi

testing - 测试中的静态文件

转载 作者:IT王子 更新时间:2023-10-29 01:26:53 25 4
gpt4 key购买 nike

当我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com