Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test code that does file IO?

Given the following class, how would you go about writing a unit test for it? I have read that any test that does file IO is not a unit test, so is this an integration test that needs to be written? I am using xUnit and MOQ for testing and I am very new to it, so maybe I could MOQ the file? Not sure.

public class Serializer
{
    public static T LoadFromXmlFile<T>(string path)
        where T : class
    {
        var serializer = new XmlSerializer(typeof(T));

        using (var reader = new StreamReader(path))
        {
            return serializer.Deserialize(reader) as T;
        }
    }

    public static void SaveToXmlFile<T>(T instance, string path)
    {
        var serializer = new XmlSerializer(typeof(T));

        using (var writer = new StreamWriter(path))
        {
            serializer.Serialize(writer, instance);

            writer.Flush();
        }
    }
}
like image 449
Sam Avatar asked Aug 15 '13 00:08

Sam


2 Answers

In similar situations I've modified the method signatures to accept a TextWriter or Stream (depending on the situation) and unit tested by passing in StringWriters or MemoryStreams and comparing the resulting string or byte array to an expected result. From there it's a fairly safe assumption that a FileWriter or FileStream will produce the same output in a file assuming the path is valid and you have the necessary permissions.

like image 131
Jesse Sweetland Avatar answered Sep 25 '22 08:09

Jesse Sweetland


Probably this an example of a test you don't need to write.

But IF you want to test the actual file level stuff. You could write out a known file to a specific location and then test the file read in's binary is the same as a pre-canned binary stream.

like image 35
AndyM Avatar answered Sep 23 '22 08:09

AndyM