CUnit的下载地址:CUnit下载
本文使用的是CUnit-2.1-3.tar.bz2
安装步骤
tar jxvf CUnit-2.1-3.tar.bz2
cd CUnit-2.1-3
./bootstrap
./configure --prefix=/opt/cunit/local
make
make install
举例
文件组织结构
- 被测试的模块
(1)文件ap_math.c
,定义了一个求和函数:int cal_num(int a, int b);
(2)头文件ap_math.h
- 测试用例和测试包
(1)文件test_ap_math.c
定义了测试用例 - 单元测试入口
(1)文件test_run.c
源代码
文件ap_math.c
#include "ap_math.h"
int cal_num(int a, int b)
{
int c;
c = a + b;
return c;
}
头文件ap_math.h
#ifndef AP_MATH_H
#define AP_MATH_H
int cal_num(int a, int b);
#endif
文件test_ap_math.c
#include <stdio.h>
#include <assert.h>
#include "Console.h"
#include "ap_math.h"
int init_suite()
{
return 0;
}
int end_suite()
{
return 0;
}
int test_is_euqal(int a, int b, int real)
{
int result;
result = cal_num(a, b);
if (result == real)
{
return 1;
}
return 0;
}
int test_is_not_equal(int a, int b, int real)
{
int result;
result = cal_num(a, b);
if (result != real)
{
return 1;
}
return 0;
}
void test1()
{
CU_ASSERT(test_is_euqal(3, 4, 7));
}
void test2()
{
CU_ASSERT(test_is_not_equal(3, 4 ,10));
}
int test_cal_module()
{
CU_pSuite p_suite = NULL;
p_suite = CU_add_suite("test_suite", init_suite, end_suite);
if (p_suite == NULL)
{
//return 1;
}
if (CU_add_test(p_suite, "test1", test1) == NULL
|| CU_add_test(p_suite, "test2", test2) == NULL)
{
return 1;
}
return 0;
}
文件test_run.c
#include <stdio.h>
#include <assert.h>
#include "Console.h"
extern int test_cal_module ();
int main(int argc, char const *argv[])
{
if (CU_initialize_registry() != CUE_SUCCESS)
{
return CU_get_error();
}
assert(CU_get_registry() != NULL);
assert(!CU_is_test_running());
if (test_cal_module() != 0)
{
CU_cleanup_registry();
return CU_get_error();
}
CU_console_run_tests();
CU_cleanup_registry();
return 0;
}
Makefile文件
all: test
CC = gcc
CFLAGS = -c -Wall
OBJS = ap_math.o \
test_ap_math.o \
test_run.o
CUNITDIR = /opt/cunit/local
INCS = -I $(CUNITDIR)/include/CUnit -L $(CUNITDIR)/lib
LIBS = -lcunit -lcurses -static
test: $(OBJS)
$(CC) $(INCS) $^ $(LIBS) -o $@
%.o: %.c
$(CC) $(CFLAGS) $(INCS) $< -o $@
clean:
rm -f $(OBJS) test
运行
Linux下输入
./test即可看到console命令界面