I'd like to write a unit-test for a method that prints to the standard output.
I have already changed the code so it prints to a passed-in File
instance instead that is stdout
by default. The only thing I am missing is some in-memory File
instance that I could pass-in. Is there such a thing? Any recommendation? I wish something like this worked:
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
?
Instead of relying on File
which is quite a low level type, pass the object in via an interface.
As you have aluded to in your comment OutputStreamWriter
in Java is a wrapper of many interfaces designed to be an abstraction over byte streams, etc. I'd 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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With