Pregunta

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();
        }
    }
}
¿Fue útil?

Solución

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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top