如何在Go中编写parseFile的测试。

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

How to write a test for parseFile in Go

问题

我有一个parseFile函数,它可以解析文件并返回一个结构体,其中包含特定的信息。我该如何为这个函数编写测试呢?在Java中,我可以在测试文件夹中放置一个文件,但是我不确定在Go语言中应该如何做得最好。

谢谢和问候。

英文:

I have a parseFile function that given a file parsing for certain information and returns a struct. How do I write a test for this function?
With Java, I could have a file in the test folder but I not sure how to best do it in Go.

Thanks and regards

答案1

得分: 3

你可以在Go语言中完全做到同样的事情,尽管处理方式有些不同。
在你的*_test.go文件旁边创建一个名为"testdata"的文件夹。

根据惯例,这个文件夹被Go工具忽略,以及所有以下划线开头的文件夹。这就是为什么我将Web应用程序的资源目录命名为"_components"而不是"bower_components"的原因。

现在,你可以使用相对路径从你的测试中访问该文件夹,而不会污染你的命名空间或其他东西。

英文:

You can do exactly the same in Go, albeit it is handled a bit differently.
Create a folder called "testdata" next to your *_test.go files.

This folder is by convention ignored by the go tools, as are all folders beginning with an underscore. This is why I name my resources directories for web applications _components instead of bower_components, for example.

Now, you can access said folder with a relative path from your tests, and it won't pollute your namespace or sth.

答案2

得分: 2

你应该能够将文件提交到与你的测试相同的文件夹中,并通过os.Open("./path_to_file")的方式读取相对路径。

如果问题是你正在寻找特定位置的文件,我建议将加载信息的方法参数化,以接受不同的文件路径。

英文:

You should be able to commit a file to the same folder as your test, and read in a relative path by way of os.Open("./path_to_file").

If the issue is that you're looking for a file in a specific location, I'd recommend parameterizing whichever method loads the information to accept different filepaths.

huangapple
  • 本文由 发表于 2016年1月21日 04:38:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/34910033.html
匿名

发表评论

匿名网友

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

确定