1

私はテストフレームワークを開発しています。多数のテスト スイートがあり、それぞれが個々のテストのメンバー関数のセットを持つクラスです。

クラス内のすべてのテストを動的に反復する方法を見つけたいと思います。

理想的なセットアップは次のようになります。

class A : public Test
{
public:
    A() {
        addTest(a);
        addTest(b);
        addTest(c);
    }

    void a() { cout << "A::a" << endl; }
    void b() { cout << "A::b" << endl; }
    void c() { cout << "A::c" << endl; }
};

addTest() メソッドは、そのパラメーターをリストに追加します。このリストは後で繰り返され、各メソッドが実行されます。

これを達成する方法はありますか?これまでに思いついた最も近いものは次のとおりです。

class Test
{
public:
    template <typename T>
    struct UnitTest
    {
        typedef void (T::*P)();
        P f;
        UnitTest(P p) : f(p) {}
    };
    // (this struct simplified: we also include a name and description)

    virtual void run(int testId) = 0;
};

class A : public Test
{
public:
    A() {
        mTests.push_back(UnitTest<A>(&A::a));
        mTests.push_back(UnitTest<A>(&A::b));
        mTests.push_back(UnitTest<A>(&A::c));
    }

    void a() { cout << "a" << endl; }
    void b() { cout << "b" << endl; }
    void c() { cout << "c" << endl; }

    // not ideal - this code has to be repeated in every test-suite
    void run(int testId)
    {
        (this->*(mTests[testId].f))();
    }
    vector<UnitTest<A>> mTests;
};

メインの実行ループの反復ごとに 1 つのテストを呼び出すには:

a->run(mTestId++);

すべてのテスト スイート (クラス) が run() コードを繰り返し、独自の mTests メンバーを持つ必要があるため、これは理想的ではありません。

理想に近づける方法はありますか?

4

1 に答える 1

1

各テストを関数または関数オブジェクトにします。テストへのポインターのコンテナーを作成してから、コンテナーを反復処理します。

struct Test_Base_Class
{
  virtual bool Execute(void) = 0;
};

typedef std::vector<Test_Base_Class *> Container_Of_Tests;

struct Test_Engine
{
  Container_Of_Tests tests_to_run;

  void Add_Test(Test_Base_Class * p_new_test)
  {
    tests_to_run.push_back(p_new_test);
  }

  void Run_Tests(void)
  {
    Container_Of_Tests::iterator iter;
    for (iter = tests_to_run.begin();
         iter != tests_to_run.end();
         ++iter)
    {
       (*iter)->Execute(); // Invoke the Execute method on a test.
    }
    return;
  }
}

これが基盤です。私は現在このパターンを使用していますが、Resume()メソッドとステータスレポートを含むように拡張しました。

于 2011-02-07T23:33:11.983 に答える