Tam*_*mas 5 unit-testing d mocking
我想为打印到标准输出的方法编写单元测试.我已经更改了代码,因此它会打印到传入的File实例,而不是stdout默认情况下.我唯一缺少的是一些File我可以传入的内存实例.有这样的事吗?有什么建议?我希望这样的事情有效:
import std.stdio;
void greet(File f = stdout) {
f.writeln("hello!");
}
unittest {
greet(inmemory);
assert(inmemory.content == "hello!\n")
}
void main() {
greet();
}
Run Code Online (Sandbox Code Playgroud)
用于打印到的单元测试代码的任何其他方法stdout?
不要依赖File相当低级的类型,而是通过接口传递对象。
正如您在 Java 的评论中提到的那样,OutputStreamWriterJava 是许多接口的包装器,旨在成为字节流等的抽象。我也会这样做:
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")
}
Run Code Online (Sandbox Code Playgroud)