C單元測試框架——CMockery簡介與示例
簡介
是google釋出的用於C單元測試的一個輕量級的框架。
主要特點:
- 免費且開源,google提供技術支援;
- 輕量級的框架,使測試更加快速簡單;
- 避免使用複雜的編譯器特性,對老版本的編譯器來講,相容性好;
- 並不強制要求待測程式碼必須依賴C99標準,這一特性對許多嵌入式系統的開發很有用;
獲取原始碼:
svn地址:svn checkout http://cmockery.googlecode.com/svn/trunk/ cmockery-read-only
編譯方法:
window下,
- 開啟使用VS2003/2005/2008 提供的 命令提示視窗;
- cd 到CMockery的目錄的window目錄
- 執行 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 中我們只有兩個功能。加法 和減法,如下:
- int add(int a, int b)
- {
- return a + b;
- }
-
int sub(int a,
- {
- return a - b;
- }
test_math.c ,對 add 和 函式的測試,以及main函式。如下:
- #include <stdarg.h>
- #include <stddef.h>
- #include <setjmp.h>
- #include <cmockery.h>
- /* Ensure add() adds two integers correctly. */
- void test_add(void **state) {
- assert_int_equal(add(3, 3), 6);
- assert_int_equal(add(3, -3), 0);
- }
- /* Ensure sub() subtracts two integers correctly.*/
- void test_sub(void **state) {
- assert_int_equal(sub(3, 3), 0);
- assert_int_equal(sub(3, -3), 6);
- }
- int main(int argc, char *argv[])
- {
- const UnitTest tests[] = {
- unit_test(test_add),
- unit_test(test_sub),
- };
- return run_tests(tests);
- }
在windows下可以直接新建一個空專案、加入 math.c test_math.c cmockery.h 以及 cmockery.lib檔案直接編譯執行即可。cmockery.lib檔案在上次文章 中已經產生。
在linux下需要使用 Makefile 編譯,其原始碼為:
- INC=-I/usr/local/include/google
- LIB=-L/usr/local/lib
- all: math.c test_math.c
- 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 ,謝謝!