最近在K2的測試項目中做了一些利用cppunit做接口測試的工作,總結了一篇使用簡介,里面有實際測試用例的svn地址,希望對有興趣的同學有所幫助。
一:下載:
地址:http://sourceforge.net/projects/cppunit/files/cppunit/
版本:最新版1.12.1
二:編譯配置
解壓后進入cppunit-1.12.1目錄執行以下操作:
./configure
make
make check
make install(sudo make install):自動將生成的.a和.so文件安裝到usr/local/lib 目錄。
手動將cppunit-1.12.1/include/下的cppunit目錄,拷貝到/usr/local/include目錄下。
三:如何寫testcase
概念理解
Testcase:一次測試,一般可以看做一次輸入,對應一次確定的輸出;
TestSuite:多個TestCase可以嵌套在一個TestSuite中,多個TestSuite又可以嵌套在更上層的TestSuite中;
一個簡單的測試實現
被測功能(只提供了加法功能的算數類):
///Math.h
// a class will be tested
class Math
{
public:
Math(){}
~Math(){}
int add(int,int);
};
算數類的實現:
///Math.cpp
//implement of Math.h
#include
#include “Math.h”
int Math::add(int x,int y)
{
return x+y;
}
-----------------------------------------------華麗的分割線-----------------------------------------------------------------
為了測試Math類的測試類:
/// MathTest.h
// A TestFixture subclass.
#include “cppunit/TestFixture.h”
#include “cppunit/extensions/HelperMacros.h”
class MathTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(MathTest); //聲明一個TestSuite
CPPUNIT_TEST(testAdd); //添加TestCase到TestSuite
/*定義新的測試用例需要在這兒聲明一下
// … 可以添加更多testcase
*/
CPPUNIT_TEST_SUITE_END();// TestSuite聲明完成
public:
MathTest(){}
~MathTest(){}
void eard(){};//初始化函數,此例沒有用到
void eardown(){};//清理函數,此例沒有用到
void testAdd ();// 測試加法的測試函數
/*可以添加更多測試函數
// …
*/
};
測試類MathTest的實現:
/// MathTest.cpp
// implement of MathTest.h
#include "MathTest.h"
#include "Math.h"
#include "cppunit/TestAssert.h"
//把這個TestSuite注冊到名字為"alltest"的TestSuite中
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( MathTest, "alltest" );
//實現測試,測試中的核心部分
void MathTest::testAdd()
{
Math M;//實例化
int ret = M.add(-1,3); //調用add方法對其進行測試;
CPPUNIT_ASSERT(ret==2); //用cppunit提供的方法對ret與預期結果作比較
}
Main函數:
#include
#include
// 如果不更改TestSuite, 本文件后期不需要更改.
int main()
{
CppUnit::TextUi::TestRunner runner;
//從注冊的TestSuite中獲取特定的TestSuite
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry("alltest");
//添加這個TestSuite到TestRunner中
runner.addTest( registry.makeTest() );
// 運行測試
runner.run();
}
編譯:
g++ Math.cpp MathTest.cpp main.cpp -lcppunit -ldl -lm -lpthread -o mathTest
運行:
export LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH
./mathTest
顯示:
通過的情況:OK (1 tests)
失敗的情況:會顯示那個測試類中的哪行測試不通過
!!!FAILURES!!!
Test Results:
Run: 1 Failures: 1 Errors: 0
1) test: MathTest::testAdd (F) line: 15 MathTest.cpp
assertion failed
- Expression: ret==4
四:實際應用
之前組內討論時,有些模塊考慮到開發測試代碼時間,以及新人上手慢的問題,我覺得也有道理,后面有時間會繼續完善測試過程,總結下什么樣的模塊適合做單元測試,以及怎么減少這種代價和風險。
五:什么樣的模塊適合做類單元測試
不能單獨運行的模塊,必須依賴上級模塊的輸出結果等情形;
提供給別的模塊做調用的,提供頭文件,.so動態庫或者.a靜態庫;
Api測試,基礎組件(kfc、mmdb)的api接口;
以上情形中,被測函數參數個數、類型不發生變化或者變化不頻繁;
測試過程中,使用了開發包裝過的工具去測試的,也可以考慮下是否可行;
待補充。
原文轉自:http://www.anti-gravitydesign.com