Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing File I/O Methods

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?

like image 579
ab217 Avatar asked Aug 10 '10 17:08

ab217


3 Answers

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.

like image 186
Gishu Avatar answered Nov 12 '22 04:11

Gishu


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

like image 39
Chubas Avatar answered Nov 12 '22 03:11

Chubas


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.

like image 2
Sulla Avatar answered Nov 12 '22 03:11

Sulla