File in memory for unittesting

I would like to write unit-test for a method that outputs to standard output. I already changed the code, so it prints an instance of the past File by default, not stdout . The only thing I am missing is some instance of File in memory that I could pass. Does something like this exist? Any recommendation? I would like this to work:

 import std.stdio; void greet(File f = stdout) { f.writeln("hello!"); } unittest { greet(inmemory); assert(inmemory.content == "hello!\n") } void main() { greet(); } 

Any other approach for unit testing code that prints to stdout ?

+5
source share
1 answer

Instead of relying on File , which is pretty low level, pass the object through the interface.

As you already mentioned in your comment, OutputStreamWriter in Java is a wrapper made up of many interfaces designed to abstract over byte streams, etc. I would do the same:

 interface OutputWriter { public void writeln(string line); public string @property content(); // etc. } class YourFile : OutputWriter { // handle a File. } void greet(ref OutputWriter output) { output.writeln("hello!"); } unittest { class FakeFile : OutputWriter { // mock the file using an array. } auto mock = new FakeFile(); greet(inmemory); assert(inmemory.content == "hello!\n") } 
+1
source

All Articles