CppUnitの使い方 3~ソースの書き方

CppUnitの使い方ラスト。

目次
1.準備
2.プロジェクトの構成
3.ソースの書き方

まずはメイン。コンソールでテキストベースに使う場合はHogeTest.cppを次のように書く。HogeTest.cppやらファイルの構成やらについては前回を参照のこと。


#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TextOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>

int _tmain(int argc, _TCHAR* argv[])
{
    CppUnit::TextUi::TestRunner runner;
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
    CppUnit::Outputter* outputter = new CppUnit::TextOutputter(&runner.result(),std::cout);
    runner.setOutputter(outputter);
    int ret = runner.run() ? 0 : 1;
    return ret;
}

Hogeクラスのテストコードは以下のようにする。


// 必要なヘッダの #include
#include "Hoge.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestAssert.h>


class Hoge_Test : public CppUnit::TestFixture {
    // テストスイート作成
    CPPUNIT_TEST_SUITE(Hoge_Test);  // クラス名を指定してテストスイート(テストの集合)を作成する。
    CPPUNIT_TEST(test_foo_001);  // 下で定義したテストコードを登録する。これを書かないとそのテストはテストされない。
    CPPUNIT_TEST_SUITE_END();
private:
    // 必要な メンバ変数/関数

    // テスト用ツール関数はこの辺に定義しとく。以下はサンプル。
    
    /**
     * 整数を文字列に変換する。
     */
    std::string itos(int i) {
        char buff[50];
        sprintf(buff, "%d", i);
        return std::string(buff);
    }

    /**
     * 乱数を発生させる。0以上N未満。
     */
    int my_rand(int N) {
        return (int)((double)rand() / ((double)RAND_MAX + 1) * N);
    }





public:

    /*
     * コンストラクタ/デストラクタ
     */
    Hoge_Test() {
    }

    ~Hoge_Test() {
    }

    /*
     * 初期化。
     * 各テストコードを実行する前に呼ばれる。
     * 内部変数を初期化したいとか、そういうのを書く。
     */
    virtual void setUp() {
    }

    /*
     * 後始末。
     * 各テストコード終了後に実行される。
     * たぶん、テストに失敗しても呼ばれるんじゃないかな。
     */
    virtual void tearDown() {
    }


    /**
     * 実際のテストコードを書く。
     * 名前はたぶんなんでもいいが、分かりやすさのため
     * test_関数名_番号()
     * としておく。引数・戻り値はvoid。
     */
    void test_foo_001() {
        Hoge instance;
        
        CPPUNIT_ASSERT(true == instance.foo());  // foo()がtrueを返すかどうかをテスト。
        CPPUNIT_ASSERT("foo test", true == instance.foo());  // 上と同じ。エラーのとき「foo test」って出る。
        CPPUNIT_ASSERT_EQUAL(true, instance.foo());  // instance.foo()がtrueと同じかのテスト。これ使わなくても上でいいんじゃね?
        CPPUNIT_ASSERT_DOUBLES_EQUAL(0.1, instance.foo(), 0.001);  // instance.foo()が0.1を返すかどうか。浮動小数点なので。誤差0.001。
        CPPUNIT_FAIL("error");  // 失敗する。エラーパスに仕込むのかな。あるいはまだ中身作ってないテストとか?
    }

};

/*
 * テストスイート(このクラスの冒頭で登録した奴)をテストとして登録。
 * これをしないとこのスイートはテストされない。
 * 逆に言うと、これさえ書いておく、あるいは消しておけばメインを変更しなくてもテストするクラスを指定できる。
 */
CPPUNIT_TEST_SUITE_REGISTRATION(Hoge_Test);

そういうわけで、privateなメソッドをテストするためにHogeクラスは以下のようにしておく。(参考:前方宣言


class HogeTester;   // 前方宣言

class Hoge {
   friend HogeTester;

private:
   bool foo;
   void bar();
};

C言語のソースでも同じように適当にテストクラス作ってテストコード作ってやればいい。ファイルスコープ関数(staticなやつ)をテストするには*.cファイルをインクルードするとかいう荒業もありか。(なしかも)

以上

コスミー について

昔(?)はゲーム作ってました。 今もなんか作ろうとしています。
カテゴリー: C++, C言語, Tips パーマリンク

CppUnitの使い方 3~ソースの書き方 への8件のフィードバック

  1. マイコーダ | PHPから.NETに移動するために私を納得させる説得しようとしています。 コスト経費私は常にためのアイデアを嫌っています。しかし、彼は何も少なくtryiongないです。 に| WordPressの可動型を私が使用してきた約一年のためのウェブサイトや午前気になる別のプラットフォームへの切り替えについて。 blogengine.net程度のもの、私は を聞いたことがあります。すべての私のワードプレス|そこにコンテンツ投稿 |私はインポート転送することができます方法はありますか? 任意の種類のヘルプは大幅されることになる感謝します!
    即日出荷 一部予約販売 http://www.benediktasvanagas.lt

  2. Concepcion のコメント:

    I do accept as true with all of the ideas you have offered
    on your post. They are very convincing and can certainly work.
    Still, the posts are too brief for novices. Could you please extend them a little from subsequent time?
    Thanks for the post.

  3. jual gamis pria のコメント:

    I am regular visitor, how are you everybody? This piece of writing posted at this
    web page is actually nice.

  4. jual pintu fiber のコメント:

    I do not know if it’s just me or if perhaps everybody else experiencing issues with your
    website. It appears like some of the text in your content
    are running off the screen. Can someone else please provide feedback and let me know if
    this is happening to them as well? This could be a problem
    with my browser because I’ve had this happen before. Cheers

  5. This is a very good tip particularly too those new to the blogosphere.
    Short but very acchurate information… Appreciate your sharing this one.
    A must read post!

  6. ピンバック: カルティエ ネックレス 人気

  7. Excellent blo уoս have here.. It’s difficult t᧐ find quality writing likme yoirs nowadays.
    Ι гeally appreciat individuals ⅼike you! Taқe care!!

  8. Edmund のコメント:

    Discover an additional table if you feel you are unable or do not want to continue
    playing at the 1 you are on. After link, it
    is simple to do a Google search for critiques of online poker reward,
    or some thing comparable. You must have fifty to one hundred occasions the
    big blind. Sometimes you may even put him on 1 Five, say, 6-5.
    One of the Best Online Casinos is Cake Poker.

コメントを残す

メールアドレスが公開されることはありません。