使用几十行代码实现一个简约的C语言单元测试框架。该框架只有一个头文件,使用方法如下:
- 引用头文件mcut.h
- 编写测试函数(测试case),参数和返回值类型均为void。测试函数中使用mcut_assert、mcut_assert_msg、mcut_assert_int对测试结果进行判断
- 调用mcut_run_test方法运行测试函数
- 调用mcut_show_statistics,展示统计结果
框架代码,mcut.h:
/* mcut.h: Minimalist C Unit Test framework */
#ifndef __MCUT_H
#define __MCUT_H
#include <stdlib.h>
#include <stdio.h>
static int __MCUT_RAN = 0;
static int __MCUT_FAILED = 0;
#define mcut_assert_msg(expr, ...) \
do { \
__MCUT_RAN++; \
if (!(expr)) { \
printf("%s(%d): ", __func__, __LINE__); \
printf(__VA_ARGS__); \
printf("\n"); \
__MCUT_FAILED++; \
} \
} while (0)
#define mcut_assert(expr) \
mcut_assert_msg(expr, "Assertion '"#expr"' failed")
/* O may be any comparion operator. */
#define mcut_assert_int(X, O, Y) \
mcut_assert_msg((X) O (Y), \
"Assertion '"#X#O#Y"' failed: "#X"==%d, "#Y"==%d", X, Y)
#define mcut_run_test(test_case) test_case()
#define mcut_show_statistics() \
do { \
float passed = 0; \
if (__MCUT_RAN != 0) { \
passed = (__MCUT_RAN - __MCUT_FAILED) * 100.00 / __MCUT_RAN; \
} \
printf("\n---------- Run Summary ----------\n"); \
printf("Passed: %.2f%%, Ran: %d, Failed: %d\n", \
passed, __MCUT_RAN, __MCUT_FAILED); \
if (__MCUT_FAILED) return 1; \
} while (0)
#endif
测试代码,test_sub.c:
#include <stdlib.h>
#include <stdio.h>
#include "mcut.h"
/* function */
int sub(int a, int b)
{
return 0;
}
/* test case */
static void test_sub1(void)
{
mcut_assert(sub(10, 5) == 5);
}
static void test_sub2(void)
{
mcut_assert_msg(sub(2, 5) == -3, "Error: sub(2, 5) != -3");
}
static void test_sub3(void)
{
mcut_assert_int(sub(2, 0), ==, 2);
}
static void test_sub4(void)
{
mcut_assert_int(sub(0, 0), ==, 0);
}
/* run test case */
int main(int argc, char *argv[])
{
mcut_run_test(test_sub1);
mcut_run_test(test_sub2);
mcut_run_test(test_sub3);
mcut_run_test(test_sub4);
mcut_show_statistics();
return 0;
}
编译
# gcc -Wall test_sub.c -o test_sub
运行结果
# ./test_sub
test_sub1(14): Assertion 'sub(10, 5) == 5' failed
test_sub2(19): Error: sub(2, 5) != -3
test_sub3(24): Assertion 'sub(2, 0)==2' failed: sub(2, 0)==0, 2==2
---------- Run Summary ----------
Passed: 25.00%, Ran: 4, Failed: 3