Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-memory File for unittesting

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?

like image 943
Tamas Avatar asked Nov 10 '22 16:11

Tamas


1 Answers

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")
}
like image 78
Gary Willoughby Avatar answered Nov 15 '22 12:11

Gary Willoughby