[英]In-memory File for unittesting
我想為打印到標准輸出的方法編寫單元測試。 我已經更改了代碼,因此它打印到傳入的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();
}
用於打印到stdout
單元測試代碼的任何其他方法?
而不是依賴於相當低級別類型的File
,而是通過接口傳遞對象。
正如你在評論中所說的那樣,Java中的OutputStreamWriter
是許多接口的包裝器,它被設計成對字節流等的抽象。我也會這樣做:
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")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.