cppunitのテンプレ

cppunitでテストコードを書くときのテンプレ。

まずは、main.cpp。これはまるこぴでおっけ。

#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>


int main(int argc, char* argv[])
{
    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that colllects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener(&result);

    // Add a listener that print dots as test run.
    CPPUNIT_NS::BriefTestProgressListener progress;
    controller.addListener(&progress);

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest(CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest());
    runner.run(controller);

    // Print test in a compiler compatible format.
    CPPUNIT_NS::CompilerOutputter outputter(&result, CPPUNIT_NS::stdCOut());
    outputter.write();

    {
        int a = 0;
        std::cin >> a;
    }

    return result.wasSuccessful() ? 0 : 1;
}
    

テスト対象のクラスがNormalRandomGeneratorとする。

テスト用のクラスとしてNormalRandomGeneratorTest.h及びNormalRandomGeneratorTest.cppを用意する。

テストクラスのsetUp及びtearDownメソッドは各テストメソッド(ここではtestOperatorParenthesis)を実行する前と後に実行されるメソッド

NormalRandomGeneratorTest.h

#pragma once

//include test target hearder.
#include "cva/random/NormalRandomGenerator.h"

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>
namespace cva_test {
    class NormalRandomGeneratorTest : public CPPUNIT_NS::TestFixture {
        CPPUNIT_TEST_SUITE(NormalRandomGeneratorTest); //class name
        CPPUNIT_TEST(testOperatorParenthesis); //nane of test
        CPPUNIT_TEST_SUITE_END();

    private:
        void testOperatorParenthesis(); //test metdho declaration

        NormalRandomGenerator *_generator;
    };
}

NormalRandomGeneratorTest.cpp

#include "NormalRandomGeneratorTest.h"
namespace cva_test {
    CPPUNIT_TEST_SUITE_REGISTRATION(NormalRandomGeneratorTest);

    void NormalRandomGeneratorTest::setUp()
    {
        _generator = new NormalRandomGenerator();
    }

    void NormalRandomGeneratorTest::tearDown()
    {
        delete _generator;
    }

    void NormalRandomGeneratorTest::testOperatorParenthesis()
    {
        //test here
    }
}

参考

テスト駆動開発とかよくわからない人のための今すぐ使えるCppUnitテンプレ - EchizenBlog-Zwei

Visual Studio C++でCppUnitをビルドできない、そんなとき | skmks