Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good approach to get rid of dependency on a StreamReader/FileStream for Unit Tests?

Here's the scenario:

I have a method that reads in a file via a FileStream and a StreamReader in .NET. I would like to unit test this method and somehow remove the dependency on the StreamReader object.

Ideally I would like to be able to supply my own string of test data instead of using a real file. Right now the method makes use of the StreamReader.ReadLine method throughout. What is an approach to modifying the design I have now in order to make this test possible?

like image 217
Kryptic Avatar asked Feb 11 '11 22:02

Kryptic


3 Answers

Depend on Stream and TextReader instead. Then your unit tests can use MemoryStream and StringReader. (Or load resources from inside your test assembly if necessary.)

Note how ReadLine is originally declared by TextReader, not StreamReader.

like image 192
Jon Skeet Avatar answered Nov 12 '22 19:11

Jon Skeet


The simplest solution would be to have the method accept a Stream as a parameter instead of opening its own FileStream. Your actual code could pass in the FileStream as usual, while your test method could either use a different FileStream for test data, or a MemoryStream filled up with what you wanted to test (that wouldn't require a file).

like image 36
Tridus Avatar answered Nov 12 '22 18:11

Tridus


Off the top of my head, I'd say this is a great opportunity to investigate the merits of Dependency Injection.

You might want to consider redesigning your method so that it takes a delegate that returns the file's contents. One delegate (the production one) might use the classes in System.IO, while the second one (for unit testing), returns the contents directly as a string.

like image 2
Mike Hofer Avatar answered Nov 12 '22 18:11

Mike Hofer