代码之家  ›  专栏  ›  技术社区  ›  Jonathan Wilbur

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

d oop
  •  2
  • Jonathan Wilbur  · 技术社区  · 8 年前

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

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

    我还能做些什么来消除每个子类将要存在的数千行单元测试的重复吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   BioTronic    8 年前

    如果您喜欢为每个子类专门化(并因此复制)的基类:

    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 ,但遗憾的是,这不起作用(当测试约束时,我们还不知道 Derived 继承自 Base!Derived ,因为这当然只有在约束通过后才会发生)。

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