目录
前言
常见C语言单元测试框架有:
Check框架
今天给大家介绍C语言单元测试框架:Check
check官网:Check | Unit testing framework for C
1、Check框架特点
2、Check框架使用
第一步:CentOS下安装ckeck
[root@k8s-master01 check]# yum install check
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirrors.ustc.edu.cn
* elrepo: mirror-hk.koddos.net
* extras: ftp.sjtu.edu.cn
* updates: ftp.sjtu.edu.cn
正在解决依赖关系
--> 正在检查事务
---> 软件包 check.x86_64.0.0.9.9-5.el7 将被 安装
--> 解决依赖关系完成
依赖关系解决
==========================================================================================
Package 架构 版本 源 大小
==========================================================================================
正在安装:
check x86_64 0.9.9-5.el7 base 102 k
事务概要
==========================================================================================
安装 1 软件包
总下载量:102 k
安装大小:354 k
Is this ok [y/d/N]: y
Downloading packages:
check-0.9.9-5.el7.x86_64.rpm | 102 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
正在安装 : check-0.9.9-5.el7.x86_64 1/1
验证中 : check-0.9.9-5.el7.x86_64 1/1
已安装:
check.x86_64 0:0.9.9-5.el7
完毕!
第二步:创建工程
工程目录结果如下:
[root@k8s-master01 check]# tree
.
├── include
│ ├── sub.h
│ └── unit_test.h
├── makefile
├── sub
│ └── sub.c
├── sub.o
└── unit_test
├── test_main.c
└── test_sub.c
3 directories, 7 files
sub.h
#ifndef _SUB_H
#define _SUB_H
int sub(int a, int b);
#endif
unit_test.h
#ifndef _UNI_TEST_H
#define _UNI_TEST_H
#include "check.h"
Suite *make_sub_suite(void);
#endif
sub.c
#include "sub.h"
int sub(int a, int b) {
return a-b;
}
test_main.c
#include "unit_test.h"
#include
int main(void) {
int n, n1;
SRunner *sr, *sr1;
sr = srunner_create(make_sub_suite()); // 将Suite加入到SRunner
srunner_run_all(sr, CK_NORMAL);
n = srunner_ntests_failed(sr); // 运行所有测试用例
srunner_free(sr);
return (n == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
How to Write a Test
test_sub.c
#include "check.h"
#include "unit_test.h"
#include "sub.h"
START_TEST(test_sub) {
fail_unless(sub(6, 2) == 4, "error, 6 - 2 != 4");
}
END_TEST
Suite * make_sub_suite(void) {
Suite *s = suite_create("sub"); // 建立Suite
TCase *tc_sub = tcase_create("sub"); // 建立测试用例集
suite_add_tcase(s, tc_sub); // 将测试用例加到Suite中
tcase_add_test(tc_sub, test_sub); // 测试用例加到测试集中
return s;
}
makefile
vpath %.h include #vpath 指定搜索路径
vpath %.c add
vpath %.c unit_test
objects = add.o test_add.o
test: test_main.c $(objects)
gcc -I include $^ -o test -lcheck
all: $(objects)
$(objects): %.o: %.c
gcc -c -I include $< -o $@
.PHONY: clean
clean:
rm *.o test
第三步:运行
直接在工程目录下运行命令make test即可生成可执行文件test,之后运行./test就可以看到测试结果了。
make test
./test
Running suite(s): sub
0%: Checks: 1, Failures: 1, Errors: 0
unit_test/test_sub.c:12:F:sub:test_sub:0: error, 6 - 2 != 4