单元测试文件I / O方法 [英] Unit Testing File I/O Methods
问题描述
看看这个如何单元测试将文件保存到磁盘?
基本上这个想法是一样的,FileSystem是你的类的依赖。所以引入一个可以在单元测试中被模拟的角色/接口(这样在单元测试时就没有依赖关系了);这个角色中的方法应该是FileSystem所需要的所有东西 -
Read $()作为一个字符串返回file_contents或者字符串[]
写入(file_contents)#同上
现在你可以使用模拟返回一个字符串数组 - 你的类可以处理这个数组。在生产代码中,角色的真正实现会碰到文件系统以返回行数组。
I am still relatively new to unit testing. I have written a class in Ruby that takes a file, searches through that file for a given Regex pattern, replaces it, then saves the changes back to the file. I want to be able to write unit tests for this method, but I don't know how I would go about doing that. Can somebody tell me how we unit test methods that deal with file i/o?
Check out this How do I unit-test saving file to the disk?
Basically the idea is the same, the FileSystem is a dependency for your class. So introduce a Role/interface that can be mocked in your unit-tests (such that you have no dependency while unit-testing); the methods in the role should be all the stuff you need from the FileSystem -
Read() # returns file_contents as a string or string[]
Write(file_contents) # same as above
Now you can use a mock to return a canned string array - your class can then process this array. In production code, the real implementation of the role would hit the filesystem to return the array of lines.
这篇关于单元测试文件I / O方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!