测试使用本地文件

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

Testing using local files

问题

我正在寻找在使用Go进行本地文件测试时应该使用的最佳实践。

使用本地文件意味着为了测试功能,应用程序需要一些本地文件,因为应用程序经常从这些文件中读取。

我不确定是否应该在运行测试之前使用ioutil包的tempdir和tempfile函数自己编写临时文件,还是创建一个测试文件夹,像这样:

testing/...test_files_here
main.go
main_test.go

然后从里面的内容读取

testing/...
英文:

I'm looking for what best practice I should use when it comes to testing with Go using local files.

By using local files, I mean that in order to test functionality, the application needs some local files, as the application reads from these files frequently.

I'm not sure if I should write temporary files myself just before running the tests using the ioutil package tempdir and tempfile functions, or create a test folder like so;

testing/...test_files_here
main.go
main_test.go

and then read from the contents inside

testing/...

答案1

得分: 20

通常会使用名为testdata的文件夹来达到这个目的,因为它会被Go工具忽略(请参阅go help packages)。

英文:

A folder named testdata is usually used for this purpose as it is ignored by the go tool (see go help packages).

答案2

得分: 9

这是我的当前测试设置:

app/
   main.go
   main_test.go
   main_testdata

   package1/
     package1.go 
     package1_test.go 
     package1_testdata1

   package2/
     package2.go 
     package2_test.go 
     package2_testdata1

所有特定于单个包的测试数据都放置在该包的目录中。将用于多个包的公共测试数据放置在应用程序根目录或$HOME中。

这个设置对我来说很有效。可以轻松更改数据并进行测试,无需额外输入命令:

vim package1_test_data1; go test app/package1

英文:

This is my current test setup:

app/
   main.go
   main_test.go
   main_testdata

   package1/
     package1.go 
     package1_test.go 
     package1_testdata1

   package2/
     package2.go 
     package2_test.go 
     package2_testdata1

All the test data that is specific to a single package, is placed within the directory of that package. Common test data that will be used by multiple packages are either placed in the application root or in $HOME.

This set up works for me. Its easy to change the data and test, without having to do extra typing:

vim package1_test_data1; go test app/package1

huangapple
  • 本文由 发表于 2015年12月8日 19:37:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/34154904.html
匿名

发表评论

匿名网友

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

确定