在Go中进行测试。如何使用虚假文件夹结构测试文件夹结构?

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

Testing in Go. How to test folder structure using fake folder structure?

问题

我正在编写一个函数,用于从源文件夹递归地复制到目标文件夹。虽然我的逻辑是正确的,但我想编写单元测试来确保所有子文件夹和文件都被正确复制。我认为使用实际的文件和文件夹并不是一个好的做法,所以我想知道如何模拟file包的函数。
具体来说,我使用file.MatchFiles(path)来获取提供路径下的所有文件和文件夹,然后我检查它是否是一个目录,以便递归地执行相同的操作。

英文:

I am writing a function to do a recursive deep copy from source folder to destination folder. While my logic works, I would like to write unit tests to ensure all sub-folders and files are getting copied correctly. I believe that using actual files and folders is not a good practice so I was wondering how to stub the file package functions.
Specifically I use file.MatchFiles(path) to get all files and folders in the path provided, then I check if it is a directory or not to do the same recursively.

答案1

得分: 1

file包是什么意思?你是不是指的os或者path/filepath?无论如何,我真的不明白你的目标是什么。例如,filepath的功能已经通过包本身的测试得到了保证。你不需要为已经包含这些测试的函数编写额外的单元测试。但是,回答你关于最佳实践的问题:这些已经包含的官方测试是使用实际文件进行测试的,所以我认为这是一个有效的方法。有道理:对于你实际想要测试的行为进行存根是一个坏主意。

因此,如果你例如使用了filepath.WalkDir(),你可以使用自定义/模拟的FileInfo实现来编写对WalkFunc的单元测试。如果你使用了另一个包,比如os,你也可以提取出自定义逻辑,并以类似的方式进行测试。如果当所有东西都结合在一起时你仍然对结果感到怀疑...好吧,那就像核心库一样使用真实的文件进行测试。

英文:

What's the file package, do you mean os or path/filepath maybe? Anyway, I don't really see what you're aiming it. The functionality of, say, filepath is already guaranteed by tests in the package itself. You don't need to write additional unit tests for functions which are already shipped with such tests. But anyway, to answer your question about good practise: These shipped, official tests work with real access to actual files, so I'ld say that's a valid approach. Makes sense: it's a bad idea to stub the behavior you actually want to test.

So, if you're for example utilizing filepath.WalkDir(), you can write unit tests for your WalkFunc with a custom/mock implementation of FileInfo. If you're using another package, e.g. os, you can also extract your custom logic and test it in a similar manner. If you're still in doubt about the result when all comes together ... well, then do it like in the core libraries did, and use real files for the test.

huangapple
  • 本文由 发表于 2022年11月13日 09:30:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/74417810.html
匿名

发表评论

匿名网友

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

确定