首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C語言單元測試框架 CUnit 完整指南

     編輯:關於C

CUnit 單元測試框架介紹

CUnit 是一個專為 C 語言設計的單元測試框架,以靜態鏈接庫形式整合至測試代碼中。它提供簡潔的測試架構建立機制,並內建豐富的斷言宏,支援通用數據類型的驗證。此外,CUnit 還提供多種測試運行與結果報告介面,方便開發者靈活選擇。

核心架構

CUnit 採用三層結構:

  • Test Registry(測試註冊表):頂層容器,單線程環境下僅存在一個有效實例。
  • Suite(測試套件):註冊表下可包含多個套件,通常按模組劃分(如一個模組對應一個 Suite)。
  • Test Case(測試用例):套件內包含多個測試函數,針對模組內部函數進行輸入調用與斷言驗證。
Test Registry
|
------------------------------
|                            |
Suite '1'  ...  Suite 'N'
|                            |
---------------        ---------------
|      |        |        |      |
Test'11'...Test'1M'  Test'N1'...Test'NM'

四種測試運行模式

模式介面類型交互性說明
AutomatedXML 文件輸出非交互結果輸出為 XML,便於自動化報告生成
Basic標準輸出非交互運行結束後在標準輸出顯示結果,不保留數據
ConsoleANSI C 控制台交互提供人機交互式控制台介面
Curses圖形介面交互僅限 Unix 系統,基於 curses 庫

基本測試流程

  1. 編寫測試函數(必要時提供 Suite 初始化/清理函數)
  2. 調用 CU_initialize_registry() 初始化測試註冊表
  3. 調用 CU_add_suite() 將 Suite 加入註冊表
  4. 調用 CU_add_test() 將測試用例加入 Suite
  5. 選擇介面運行測試(如 CU_console_run_tests())
  6. 調用 CU_cleanup_registry() 清理註冊表

完整代碼示例

被測模組 (test.h / test.c)

/* 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; }

測試主程式 (testmain.c)

#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;
}

運行入口 (CUnitRunTest.c)

#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;
}

Makefile

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

參考資料

  1. CUnit 詳細教程
  2. CUnit 實戰經驗
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved