从D中的抽象类运行单元测试?

时间:2017-10-23 12:41:37

标签: oop d

我想从抽象类而不是从它继承的具体类中运行单元测试。我尝试了一些无法编译的东西:

unittest(this T) { ... }

abstract class Parent(this T) : GrandParent
{
    ...
    unittest
    {
        T x = new T();
        x.something = true;
        assert(x.something == true);
    }
    ...
}

我还能做些什么来去除数千行单元测试,这些单元测试原本会存在于每个子类中吗?

1 个答案:

答案 0 :(得分:2)

如果您对每个子类的专用(并​​因此重复)的基类感到满意:

abstract class Base(T) {
    static assert(is(T : typeof(this)), "Tried to instantiate "~typeof(this).stringof~" with type parameter "~T.stringof);
    unittest {
        import std.stdio : writeln;
        auto a = new T();
        writeln(a.s);
    }
}

class Derived : Base!Derived {
    string s() {
        return "a";
    }
}

而不是static assert,我更倾向于在Base上设置模板约束,但遗憾的是,这并不起作用(当约束经过测试时,我们不会#&## 39;但是我知道Derived是否继承自Base!Derived,因为这只会在约束过去之后发生。当然)。

这种模式在C ++中称为Curiously Recurring Template Pattern (CRTP)