How do you check the code that the IO file does?

Given the following class, how are you going to write unit test for it? I read that any test that the IO file does is not a unit test, so is it an integration test that needs to be written? I use xUnit and MOQ for testing, and I am very new to this, so maybe I can MOQ 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(); } } } 
+6
source share
2 answers

In such situations, I modified the method signatures to receive a TextWriter or Stream (depending on the situation) and a module verified by passing to StringWriters or MemoryStreams and comparing the resulting array of strings or bytes with the expected result. From there, it's a pretty safe assumption that FileWriter or FileStream will produce the same result in a file, assuming the path is valid and you have the necessary permissions.

+6
source

Perhaps this is an example of a test that you do not need to write.

But if you want to check the actual material at the file level. You can write a known file to a specific location, and then verify that the file read in binary format matches the pre-programmed binary stream.

+1
source

Source: https://habr.com/ru/post/951767/


All Articles