Cmockery学习

什么是cmockery?

是一个轻量级的C语言单元测试框架

什么是单元测试?

单元测试就是测试一个系统的最小实现单元,往往是函数

示例解析

#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmockery.h>
//测add方法
void test_add(void **state) {
	assert_int_equal(add(3, 3), 6); //这个叫断言宏,简单地说就是通过assert这个函数判断括号内的,真就忽略继续,假就停
	assert_int_equal(add(3, -3), 0);
}
//测sub方法
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[] = { //这个是待测试的所有方法列表,每一个待测试的方法都要写一个test_xxx并用unit_test包裹
        unit_test(test_add),
		unit_test(test_sub),
    };
    return run_tests(tests); //所有的待测试方法列表(数组)传入run_tests函数,一起跑
}

  • 不能显示断言成功的表达式,因为是基于assert()的
  • cmokery会在一个进程中测试全部用例,所以当有用例失败导致内存问题时,后面的用例都没法测了,所以对malloc() 、 calloc() 和free() 的调用分别替换成test_malloc() 、test_calloc() 和 test_free()

单元测试最好能脱离原函数的环境

我现在有个函数是a,里面调用了b或者需要用到c数据库的数据,那么测试a就不要涉及bc,可以把调用bc的地方直接替换为相应数据

  • Cmockery 提供了给模拟函数的每个测试用例存放返回值的功能,使用的是 will_return() 函数。然后,这些值将通过每个模拟函数调用mock() 返回

  • 传给will_return() 的值,将分别添加到每个函数所特有的队列中去。连续调用 mock() ,将从函数的队列中移除一个返回值。

此外

  • 还有expect_xxx检测参数,
  • test_error等测试状态函数
posted @ 2023-09-08 16:45  __Zed  阅读(107)  评论(0)    收藏  举报