天天看点

d测试返回空的函数

​​原文​​ 我有下面的类:

class A {
  int[] array;

  ...

  void print() {
    writeln("array = ", this.array);
  }
}      

是否可用​

​assert​

​​来测试​

​print​

​​函数,对​

​stdout​

​的输出,如下?

A myClass= new A;
myClass.array = [1,2];
assert(myClass.print() == "array = [1,2]");      

可重定向​

​stdout​

​​到你选的文件,再测试​

​该文件​

​​.

尽管最好按​​

​参数​

​​来打印某种​

​输出区间​

​​或​

​Appender​

​,然后再测试它.

​最简单​

​​方法是​

​修改​

​​函数,使其可​

​输出​

​​到非​

​stdout​

​​,让它输出到​

​unittest​

​​中的​

​一个文件​

​​,并检查​

​文件内容​

​​来验证结果.

如:

import std.stdio;

class A
{
    int[] a;

    this(int[] a) { this.a = a; }

    void print(File output = stdout) {
        output.writeln("array = ", this.a);
    }//输出
}

unittest {
    import std.file;

    A a = new A([1, 2]);
    a.print(File("test.txt", "wb"));
    assert(readText("test.txt") == "array = [1, 2]\n");
//断定内容.
}      

类似​

​PaulBackus​

​​的程序,但我会尽量避免​

​单元测试​

​​中使用​

​文件系统​

​​.这里,可打印到​

​接收器(sink)​

​中:

import std.stdio;

class A
{
    int[] a;

    this(int[] a) { this.a = a; }

    void toString(scope void delegate(in char[]) sink) const {
        import std.conv : text;
        sink("array = ");
        sink(this.a.text);
// 或this.a.to!string

        // 较重量级替代:
        // import std.format : formattedWrite;
        // sink.formattedWrite!"array = %s"(this.a);
    }

    void print() {
        writeln(this);
    }
}

unittest {
    import std.file;

    A a = new A([1, 2]);

    import std.conv : text;
    assert(a.text == "array = [1, 2]");
}

void main() {}      

​toString​

​​是对象的​

​文本表示​

​​.如果不想得到​

​相同输出​

​​,可用与​

​toString​

​​不同的名,但这时必须使用​

​显式​

​​的​

​"sink"​

​,最好上面.

void myfunc(File = std.stdio.File)(File output = stdout) {
    output.writeln(...);
}

unittest {
    struct MockFile {
        string output;
        void writeln(Args...)(Args args) {
            output ~= format(args);
        }
    }
    MockFile mock;
    myfunc(mock);
    assert(mock.output == ...);
}      
auto original = stdout; // 保存
stdout.open(newdest, "wt"); // 重定向

// 干活.

stdout = original; // 恢复