cppunit の使い方のメモ

目次

  • gcc のオプションの調べ方
  • テストクラスの作り方 (チートシート)
  • testmain.cpp (コピペ用)
  • 参考リンク集


CppUnit のコードの書き方は、既知のものとして話を進めます。初めての方は、最後のリンクを参考にしてみてください。

gcc のオプションの調べ方

CppUnit が既にインストールされている場合 cppunit-config コマンドで、gcc のオプションをチェックできます。

$ cppunit-config

と引数を指定しないと、cppunit-config コマンドの使い方を表示します。

gcc のオプションを調べるには、

$ cppunit-config --cflags # コンパイルオプションを調べる
$ cppunit-config --libs # リンクオプションを調べる

で、出来ます。


cygwin 特有ぽいこと

  • -Wl,--enable-auto-import リンカオプションを指定した方がいいみたいです。指定しないと gcc に怒られます。
  • MinGW を使う (-mno-cygwin を指定する) と、CppUnit にリンクできません。CppUnit が最初から入っているのは gcc だけです。

テストクラスの作り方 (チートシート)

とりあえず参考リンク

  • #include
  • #include
  • CPPUNIT_NS::TestFixture を継承する
  • CPPUNIT_TEST_SUITE(クラス名);
  • CPPUNIT_TEST(テストメソッド名); × 必要なだけ
  • CPPUNIT_TEST_SUIT_END();
  • public: void setUp(void) をオーバーライド
  • public: void tearDown(void) をオーバーライド
  • テストメソッドを実装する (protected: 推奨)
  • CPPUNIT_TEST_SUITE_REGISTRATION(クラス名);

testmain.cpp (コピペ用)

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

#ifdef _MSC_VER
	#include <crtdbg.h>
#endif

int main() {
#ifdef _MSC_VER
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

	CPPUNIT_NS::TestResult controller;

	// Add a listener to collect the test results.
	CPPUNIT_NS::TestResultCollector collected_results;
	controller.addListener(&collected_results);

	// Add a listener to show progress.
	CPPUNIT_NS::BriefTestProgressListener progress;
	controller.addListener(&progress);

	// Run all the tests.
	CPPUNIT_NS::TestRunner test_runner;
	test_runner.addTest(CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest());
	test_runner.run(controller);

	// Write the results out to stdout.
	CPPUNIT_NS::CompilerOutputter outputter(&collected_results, CPPUNIT_NS::stdCOut());
	outputter.write();

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

参考リンク集

//www.evocomp.de/tutorials/tutorium_cppunit/howto_tutorial_cppunit_en.html">Unit-tests with C++ using the framework CppUnit - EvoComp:コンパクトにまとまってます。英語。
//www.atmarkit.co.jp/fdotnet/cpptest/index/index.html">C++開発者のための単体テスト入門 - @IT:簡単な解説
//www.02.246.ne.jp/~torutk/cxx/cppunit/index.html">ユニットテスト by CppUnit:多少詳しい解説"