I have a method that takes a FileInfo
object as parameter and checks whether the corresponding file is encoded in UTF-8.
I have written some unit tests for it with MSTest using real text files added to the UnitTest project, which are deployed with the DeploymentItem
attribute. I then create FileInfo
objects pointing to the deployed files and test the method with them. Like this:
[TestMethod]
[DeploymentItem(@"..\..\Import\UTF8.txt")]
public void TestUTF8Detection()
{
FileInfo fileInfo = new FileInfo("UTF8.txt");
bool isUTF8= FormatVerification.IsUTF8(fileInfo);
Assert.IsTrue(isUTF8);
}
However, I've read that using real files could be slower and less trustworthy (like here and here), so I'm thinking how would I do this mocking the files. I think I would have to:
- Create a sub-method which will be in fact tested, not the original
one which would just call it, and which takes as an argument a
FileStream
instead of aFileInfo
. - Create a
FileStream
encoded (or not) in UTF-8 and pass it to the sub-method.
So, I have some questions, from more concrete to more general:
- How can I create a
FileStream
object encoded in UTF-8 without a real file to read from? - Is the creation of this sub-method the only alternative to allow mocking the files?
- What about the original method? Can I test it in some way?
- Is creating this sort of sub-methods (only to allow unit testing ) considered to be a good practice?
- Should I really try to avoid using real files in unit tests, or are there cases like this one which justify it?