开发者

Unit Testing File I/O Methods

开发者 https://www.devze.com 2023-01-11 04:00 出处:网络
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 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 开发者_如何学Cmethod, 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.


You could create a file with known contents, do your replacement method, and then validate the contents of the modified file with the desired result.

I'd suggest using temporary files http://ruby-doc.org/core/classes/Tempfile.html for each run, and have a good read at unit testing framework http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html


If you are passing a file object to your method; try creating a dummy file object, use some i/o data streams to add contents to the file object and pass it to the method being tested.

If you are just passing the contents of the object using some datastream, create a dummy datasream and pass it to the method.

You can also opt to have a dummy file and create a file object from that file path and pass it to your method being tested.

0

精彩评论

暂无评论...
验证码 换一张
取 消