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

CPPUTest 單元測試框架 C 語言實戰指南:安裝、編寫測試、內存洩漏檢測

     編輯:關於C語言

安裝方式

  • apt-get:sudo apt-get install cpputest(版本較舊)。
  • 源碼編譯:./configure && make,直接使用編譯產出的庫與頭文件。

待測代碼結構

// sample.h
struct Student { char* name; int score; };
void ret_void(void);
int ret_int(int, int);
double ret_double(double, double);
char* ret_pchar(char*, char*);
struct Student* init_student(struct Student*, char*, int);

用 #ifndef CPPUTEST 隔離 main,便於測試編譯時排除。

測試用例編寫

// test.c
#include <CppUTest/CommandLineTestRunner.h>
#include <CppUTest/TestHarness.h>
extern "C" { #include "sample.h" }

TEST_GROUP(sample) {
    void setup() { printf("測試開始...\n"); }
    void teardown() { printf("測試結束...\n"); }
};

TEST(sample, ret_int_success) {
    CHECK_EQUAL(3, ret_int(1,2));
}
TEST(sample, ret_int_failed) {
    CHECK_EQUAL(4, ret_int(1,2)); // 故意失敗
}

int main(int argc, char* argv[]) {
    return CommandLineTestRunner::RunAllTests(argc, argv);
}

斷言宏速查

宏用途
CHECK(cond)條件為真通過
CHECK_EQUAL(exp, act)期望值==實際值
STRCMP_EQUAL(exp, act)字串比較
LONGS_EQUAL(exp, act)長整數比較
DOUBLES_EQUAL(exp, act, tol)浮點數容差比較
POINTERS_EQUAL(exp, act)指針比較
FAIL(msg)強制失敗

Makefile 關鍵配置

CPPUTEST_HOME = /path/to/cpputest
CC = gcc
CPP = g++
CFLAGS = -g -Wall -std=c99 -D CPPUTEST
CPPFLAGS = -g -Wall -I$(CPPUTEST_HOME)/include
LDFLAGS = -L$(CPPUTEST_HOME)/lib -lCppUTest
MEMFLAGS = -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h

test: test.o sample.o
    $(CPP) -o $@ $^ $(LDFLAGS)
test.o: test.c
    $(CPP) -c $< $(CPPFLAGS) $(MEMFLAGS)
sample.o: sample.c
    $(CC) -c $< $(CFLAGS) $(MEMFLAGS)

運行參數

  • ./test:默認運行。
  • -c:彩色輸出。
  • -v:詳細模式。
  • -r N:重複運行 N 次。
  • -g GROUP:指定群組。
  • -n TEST:指定單個測試。

內存洩漏檢測

編譯時加入 MEMFLAGS,測試代碼中故意 malloc 不 free,輸出將精確定位洩漏文件、行號、大小與堆棧內容。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved