You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用cmocka的will_return()向C Mock函数传递double值?

CMocka处理double类型Mock值丢失精度问题的解决方案

我在用CMocka给C项目做单元测试,需要Mock被测函数里调用的其他模块函数,该函数处理的是double类型而非整数。根据will_return的文档说明,它仅传递整数值,实际测试中发现,调用will_return(__wrap_other_func, 42.99)后,在__wrap_other_func中通过double value = mock_type(double)获取到的值为42.0,而非预期的42.99,导致断言失败。

问题代码示例

double __wrap_other_func(double param) {
  check_expected(param);
  double value = mock_type(double); // will_return() 进行了转换,相当于取整
  fprintf(stderr, "%lf\n", value);
  return value;
}

static void test_this_func(void **state) {
  (void) state;
  expect_value(__wrap_other_func, param, 1.0);
  will_return(__wrap_other_func, 42.99);
  int result = this_func(12.34); // this_func() 会调用 other_func()
  ...
  assert(result == 0); 
  /* 断言失败,因为double值42.99被转换为整数后再转回double,丢失了小数部分。 */
}

42.0

我查阅了CMocka文档并在线搜索相关示例,但未找到解决方法。


2023-11-19 更新:已找到解决方案

Andreas Schneider更新了CMocka主仓库,使Mock可以正常处理实数(float和double)。安装2023-11-17的主分支版本后,代码可正常运行。

修改后的代码示例

double __wrap_other_func(double param) {
  // 验证传入mock的参数是否符合预期
  check_expected(param);
  // 赋值返回值
  double value = mock_float; 
// will_return_float() 可处理实数(double和float)
  fprintf(stderr, "%lf\n", value); // 现在会打印真实的数值
  return value;
}

static void test_this_func(void **state) {
  (void) state;
  // 确保传入mock的参数正确
  expect_value(__wrap_other_func, param, 1.0);
  // 指定mock的返回值
  will_return_float(__wrap_other_func, 42.99);
  // 正常调用this_func,会触发other_func的mock
  int result = this_func(12.34); // this_func() 会调用 other_func()
  ...
  assert(result == 0); 
  // 断言通过,因为double值42.99保持了原有精度
}

42.99

内容的提问来源于stack exchange,提问作者Tom Willis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 02:25:39