While working on the HTML Combiner, I ran into a situation where I was trying to test a method that wrote a configuration file. This method makes heavy use of FileStream, and so the resulting test would have been coupled to the filesystem. This seems like a common issue you would run into, and there are a few ways to approach the unit test for such a method:
Option (2) seems like a good idea because you can stub the IDataSource interface in the unit test. In fact, I probably will do this later on (I admit, I was rushed for time!). This means that you will have to change your method's code to use the interface instead of changing "FileStream" to "Stream," but it's a more elegant solution that does not depend on Stream at all.
Option (3) is the one I went with, and isn't a terrible solution. By using a Stream object in the target method, you no longer depend on the FileStream (and consequently the file system). In your test for example, you can pass in a MemoryStream which contains a test "file" whose contents are in a string you declare. However, I did encounter some disadvantages:
- Allow the filesystem dependency
- Create an "IDataSource" interface and make an implementation that wraps the FileStream object
- Instead of using FileStream, use its parent, Stream, in the method you're trying to test
Option (2) seems like a good idea because you can stub the IDataSource interface in the unit test. In fact, I probably will do this later on (I admit, I was rushed for time!). This means that you will have to change your method's code to use the interface instead of changing "FileStream" to "Stream," but it's a more elegant solution that does not depend on Stream at all.
Option (3) is the one I went with, and isn't a terrible solution. By using a Stream object in the target method, you no longer depend on the FileStream (and consequently the file system). In your test for example, you can pass in a MemoryStream which contains a test "file" whose contents are in a string you declare. However, I did encounter some disadvantages:
- You still have a dependency on Stream, instead of using a stub
- You have to specify the encoding your string uses in order to create a MemoryStream out of it
- Creating and writing to the MemoryStream is not painless
No comments:
Post a Comment