It seems I keep running into situations where I want to mock or stub a class that is responsible for saving something out to disk. The problem is that using a StreamWriter (or similar) is the lifetime of the writer object is shorter than the containing class, which makes it impossible to mock effectively.
Often the way around this is to implement an interface with three method calls: Open, Write, Close - so you can reuse the writer instance for multiple files thus changing the lifetime of the writer to the same as the containing class thus allowing you to mock the writer.
I've never liked this solution, it always has felt like a workaround for testability. Instead, how about splitting the two parameters (contents and file path) into separate fluent method calls and having the Write auto-close the file like this example:
keyWriter.Write(exportKeys).To(destinationFolder);
...
public interface IExportKeyWriter
{
IExportKeyWriter Write(ImageExportKeys keys);
void To(string destinationFolder);
}
I like it because its very readable and more importantly its mockable. I can inject a single instance of the IExportKeyWriter into my class under test. When Write is called, the object is queued for writing to disk, and when To is called the destination file is opened, written to (using the queued object), and finally closed.
The only Problem I can think of is that it may not be obvious that you need to call the To method to have the file actually written out.
I'm hoping for some feedback on this, so I ask dear reader, what do you think?
Powered by: newtelligence dasBlog 2.1.8102.813
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Shawn Neal
E-mail