1. 程式人生 > >C單元測試框架——CMockery簡介與示例

C單元測試框架——CMockery簡介與示例

簡介

是google釋出的用於C單元測試的一個輕量級的框架。

主要特點:

  1. 免費且開源,google提供技術支援;
  2. 輕量級的框架,使測試更加快速簡單;
  3. 避免使用複雜的編譯器特性,對老版本的編譯器來講,相容性好;
  4. 並不強制要求待測程式碼必須依賴C99標準,這一特性對許多嵌入式系統的開發很有用;

獲取原始碼:

svn地址:svn checkout http://cmockery.googlecode.com/svn/trunk/ cmockery-read-only

編譯方法:

window下,

  1. 開啟使用VS2003/2005/2008 提供的 命令提示視窗;
  2. cd 到CMockery的目錄的window目錄
  3. 執行 nmake 命令

E: 
cd E:/OpenSource/c/cMockery 
cd windows 
nmake

cmockery.lib檔案以及一些測試程式碼都在 Windows目錄下;

linux下,

cd 到 cMockery 原始碼目錄

sudo ./configure

sudo make

sudo make install

庫檔案安裝到:/usr/local/lib

標頭檔案安裝到:/usr/local/include/google

注意此時還應該載入一下CMockery庫:

cd /usr/local/lib

sudo ldconfig

下一文章我們會介紹一個簡單例子,更多內容請參考:CMockery Manual。

歡迎轉載,請註明來自see-see ,謝謝!


示例

使用CMockery做單元測試,文中的例子從CMockery的calculator example 中剝離出來的。 

首先新建一個資料夾:math_demo,此資料夾中有三個檔案:

  • math.c            待測程式碼模組;
  • test_math.c    測試用例 和 main 函式;
  • Makefile          組織編譯

math.c 中我們只有兩個功能。加法 和減法,如下: 

  1. int add(int a, int b)   
  2. {  
  3.     return a + b;  
  4. }  
  5. int sub(int a, 
    int b)   
  6. {  
  7.     return a - b;  
  8. }   

test_math.c ,對 add 和 函式的測試,以及main函式。如下:

  1. #include <stdarg.h>
  2. #include <stddef.h>
  3. #include <setjmp.h>
  4. #include <cmockery.h>
  5. /* Ensure add() adds two integers correctly. */
  6. void test_add(void **state) {  
  7.     assert_int_equal(add(3, 3), 6);  
  8.     assert_int_equal(add(3, -3), 0);  
  9. }  
  10. /* Ensure sub() subtracts two integers correctly.*/
  11. void test_sub(void **state) {  
  12.     assert_int_equal(sub(3, 3), 0);  
  13.     assert_int_equal(sub(3, -3), 6);  
  14. }  
  15. int main(int argc, char *argv[])   
  16. {  
  17.     const UnitTest tests[] = {  
  18.         unit_test(test_add),  
  19.         unit_test(test_sub),  
  20.     };  
  21.     return run_tests(tests);  
  22. }  

在windows下可以直接新建一個空專案、加入 math.c test_math.c   cmockery.h 以及 cmockery.lib檔案直接編譯執行即可。cmockery.lib檔案在上次文章 中已經產生。

在linux下需要使用 Makefile 編譯,其原始碼為:

  1. INC=-I/usr/local/include/google  
  2. LIB=-L/usr/local/lib  
  3. all: math.c test_math.c  
  4.     gcc -o math_test_run $(INC) $(LIB) -lcmockery $^  

要確保CMockery環境已經安裝成功。詳見上次文章 。

執行make後,執行 math_test_run 結果如下:

[email protected]:~/code/unit_test/cmockery/demo/test_math$ make 
gcc -o math_test_run -I/usr/local/include/google -L/usr/local/lib -lcmockery math.c test_math.c
[email protected]:~/code/unit_test/cmockery/demo/test_math$ ./math_test_run 
test_add: Starting test
test_add: Test completed successfully.
test_sub: Starting test
test_sub: Test completed successfully.
All 2 tests passed

歡迎轉載,請註明來自see-see ,謝謝!