C单元测试框架——CMockery (2) 加减法demo

上一次文章 中我们对cmockery做了一些简单的介绍,并完成了测试环境的搭建。这次我们会讨论如何使用它做单元测试,文中的例子从CMockery的calculator example 中剥离出来的。

首先新建一个文件夹:math_demo,此文件夹中有三个文件:

  • math.c            待测代码模块;
  • test_math.c    测试用例 和 main 函数;
  • Makefile          组织编译

math.c 中我们只有两个功能。加法 和减法,如下:

int add(int a, int b) 
{
return a + b;
}
int sub(int a, int b) 
{
return a - b;
}

test_math.c ,对 add 和 函数的测试,以及main函数。如下:

#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include "cmockery.h"

/* Ensure add() adds two integers correctly. */
void test_add(void **state) {
assert_int_equal(add(3, 3), 6);
assert_int_equal(add(3, -3), 0);
}

/* Ensure sub() subtracts two integers correctly.*/
void test_sub(void **state) {
assert_int_equal(sub(3, 3), 0);
assert_int_equal(sub(3, -3), 6);
}


int main(int argc, char *argv[]) 
{
const UnitTest tests[] = 
{
unit_test(test_add),
unit_test(test_sub),
};
run_tests(tests);
getch(); 
return 0;
}

在windows下可以直接新建一个空项目、加入 math.c test_math.c   cmockery.h 以及 cmockery.lib文件直接编译运行即可。cmockery.lib文件在上次文章 中已经产生。

在linux下需要使用 Makefile 编译,其源码为:

INC=-I/usr/local/include/google
LIB=-L/usr/local/lib
all: math.c test_math.c
gcc -o math_test_run $(INC) $(LIB) -lcmockery $^

要确保CMockery环境已经安装成功。详见上次文章 。

执行make后,运行 math_test_run 结果如下:

sw2@grady:~/code/unit_test/cmockery/demo/test_math$ make 
gcc -o math_test_run -I/usr/local/include/google -L/usr/local/lib -lcmockery math.c test_math.c
sw2@grady:~/code/unit_test/cmockery/demo/test_math$ ./math_test_run 
test_add: Starting test
test_add: Test completed successfully.
test_sub: Starting test
test_sub: Test completed successfully.
All 2 tests passed

欢迎转载,请注明来自see-see ,谢谢!

转载请注明:来自Come to See-See! 
本文地址:http://see-see.appspot.com/?p=10005

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值