2014年7月19日 星期六

[CPP] Unit Test for C++ Usage via CppUnit @ Ubuntu 14.04

隨著時間越來越少後,不知不覺更在意"成果"是否能夠年年累積。想了一會兒後,最佳的方式就是引進軟工管理,除了最基本的版本控制外,幫自己把玩的小玩意 open source 及增加 reuse 的機會也很重要,維護方面則是從簡易人眼的測試改成更制式的 unit test 架構,最好能夠定時批次測試等。只不過採用制式的 unit test 不見得適合 startup 環境,畢竟時間寶貴,有些 prototype 生命週期很短。

在此以 CppUnit 為例,筆記一下怎樣快速使用,更多簡介請參考 CppUnit 文件

安裝:

$ sudo apt-get install libcppunit-dev

$ vim t.cpp
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestResult.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/BriefTestProgressListener.h>

class SampleTest : public CppUnit::TestFixture {
private:
int a;
public:
void setUp() {
a = 0;
}
void tearDown() {
a = 0;
}
static CppUnit::Test *suite() {
CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite( "SampleTest" );
suiteOfTests->addTest( new CppUnit::TestCaller<SampleTest>(
"testSample",
&SampleTest::testSample
));
return suiteOfTests;
}
void testSample() {
CPPUNIT_ASSERT( a == 10 );
}
};

int main() {
std::cout << "\n\n=== Style 1 ===\n\n";
{
CppUnit::TestCaller<SampleTest> test ( "testSample", &SampleTest::testSample );

CppUnit::BriefTestProgressListener progress;
CppUnit::TestResultCollector collectedresults;
CppUnit::TestResult result;
result.addListener(&progress);
test.run( &result );

CppUnit::CompilerOutputter outputter( &collectedresults, std::cerr );
}

std::cout << "\n\n=== Style 2 ===\n\n";
{
CppUnit::TestSuite suite;
suite.addTest( new CppUnit::TestCaller<SampleTest>(
"testSample",
&SampleTest::testSample
));

CppUnit::BriefTestProgressListener progress;
CppUnit::TestResultCollector collectedresults;
CppUnit::TestResult result;
result.addListener(&progress);
suite.run( &result );

CppUnit::CompilerOutputter outputter( &collectedresults, std::cerr );
}

std::cout << "\n\n=== Style 3 ===\n\n";
{
CppUnit::TextUi::TestRunner runner;
runner.addTest( SampleTest::suite() );
runner.run();
}
return 0;
}


測試成功:

=== Style 1 ===

testSample : OK


=== Style 2 ===

testSample : OK


=== Style 3 ===

.


OK (1 tests)


測試失敗:

=== Style 1 ===

testSample : assertion


=== Style 2 ===

testSample : assertion


=== Style 3 ===

.F


!!!FAILURES!!!
Test Results:
Run:  1   Failures: 1   Errors: 0


1) test: testSample (F) line: 27 t.cpp
assertion failed
- Expression: a == 10


目前大概打算對自定的 class 編寫一些偏邏輯層面的 unit test,例如 bool testFunc1(); 的方式,成功就回傳 true,但不套用任何 unit test framework,如此一來純邏輯的驗證更可以適用在不同平台,而要再加上特定的 unit test framework (如 CppUnit) 時,只需簡易套用,可以直接 reusable 而不必重頭寫。

沒有留言:

張貼留言