单元测试

        网上看了一篇“三行代码搞定单元测试”的博客,感觉很经典;不知道原创是哪位高人,这里直接拿过来用了。
        我将代码按照自己的思路稍微做了点修改,便于理解。
        这个简小单元测试框架的本质思想是:比较“预期值”与“输出结果”,判断用例是否通过。
        测试框架流程包括:测试初始化、测试执行、结果分析。整个控制层都在框架中实现,用例就是数据层,结果是展示层。
        实际上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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值