CUnit 是一個專為 C 語言設計的單元測試框架,以靜態鏈接庫形式整合至測試代碼中。它提供簡潔的測試架構建立機制,並內建豐富的斷言宏,支援通用數據類型的驗證。此外,CUnit 還提供多種測試運行與結果報告介面,方便開發者靈活選擇。
CUnit 採用三層結構:
Test Registry | ------------------------------ | | Suite '1' ... Suite 'N' | | --------------- --------------- | | | | | Test'11'...Test'1M' Test'N1'...Test'NM'
| 模式 | 介面類型 | 交互性 | 說明 |
|---|---|---|---|
| Automated | XML 文件輸出 | 非交互 | 結果輸出為 XML,便於自動化報告生成 |
| Basic | 標準輸出 | 非交互 | 運行結束後在標準輸出顯示結果,不保留數據 |
| Console | ANSI C 控制台 | 交互 | 提供人機交互式控制台介面 |
| Curses | 圖形介面 | 交互 | 僅限 Unix 系統,基於 curses 庫 |
CU_initialize_registry() 初始化測試註冊表CU_add_suite() 將 Suite 加入註冊表CU_add_test() 將測試用例加入 SuiteCU_console_run_tests())CU_cleanup_registry() 清理註冊表/* test.h */
#ifndef __TEST_H_
#define __TEST_H_
int sum(int a, int b);
#endif
/* test.c */
#include "test.h"
int sum(int a, int b) { return a + b; }
#include "test.h" #include#include int InitSuite(void) { return 0; } int EndSuite(void) { return 0; } void Test1(void) { CU_ASSERT(sum(3,4) == 7); } void Test2(void) { CU_ASSERT(sum(4,5) != 10); } int AddTestMain(void) { CU_pSuite pSuite = CU_add_suite("testSuite", InitSuite, EndSuite); if (!pSuite) return 1; if (!CU_add_test(pSuite, "Test1", Test1) || !CU_add_test(pSuite, "Test2", Test2)) return 1; return 0; }
#include#include extern int AddTestMain(); int main() { if (CU_initialize_registry() != CUE_SUCCESS) return CU_get_error(); if (AddTestMain() != 0) { CU_cleanup_registry(); return CU_get_error(); } CU_console_run_tests(); // 交互式控制台 CU_set_output_filename("TestMax"); CU_automated_run_tests(); // 自動化 XML 輸出 CU_cleanup_registry(); return 0; }
INC=-I/usr/local/include
LIB=-L/usr/local/lib
all: test.c testmain.c CUnitRunTest.c
gcc $^ -o test $(INC) $(LIB) -lcunit
clean:
rm -f test
若遇到庫加載問題,執行:export LD_LIBRARY_PATH=/usr/local/lib