网上看了一篇“三行代码搞定单元测试”的博客,感觉很经典;不知道原创是哪位高人,这里直接拿过来用了。
我将代码按照自己的思路稍微做了点修改,便于理解。
这个简小单元测试框架的本质思想是:比较“预期值”与“输出结果”,判断用例是否通过。
测试框架流程包括:测试初始化、测试执行、结果分析。整个控制层都在框架中实现,用例就是数据层,结果是展示层。
实际上CPPUNIT也是用的这种思路,只是CPPUNIT封装的更好,对测试套、测试用例有统一的管理;对测试日志、测试报告打印更完善;扩展性、可用性更强,很容易添加新的测试套和测试用例。
/* 框架*/
#ifndef _UNIT_TEST_H
#define _UNIT_TEST_H
#define UnitTest_CHECK(log, expect, output) do { if (!(expect == output)) return log; } while (0)
#define UnitTest_RUN(test_case) do { char *log = test_case(); num_tests++; if (log) return log; } while (0)
extern int num_tests;
#endif
#include <stdio.h>
//#include "unittest.h"
int num_tests = 0;
//期望值
int expect_foo = 7;
int expect_bar = 5;
//测试用例 testcase_foo
static char * testcase_foo()
{
int output = 7;
UnitTest_CHECK("error, in testcase_foo expect_foo != test output", expect_foo, output);
return 0;
}
//测试用例 testcase_bar
static char * testcase_bar()
{
int output = 3;
UnitTest_CHECK("error, in testcase_bar expect_bar != output", expect_bar, output);
return 0;
}
//测试套
static char * test_suit()
{
UnitTest_RUN(testcase_foo);
UnitTest_RUN(testcase_bar);
return 0;
}
int main(int argc, char **argv)
{
char *result = test_suit();
if (result != 0)
{
printf("%s\n", result);
}
else
{
printf("ALL TESTS PASSED\n");
}
printf("Tests run: %d\n", num_tests);
return result != 0;
}