简体   繁体   中英

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 ?

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM