如何使用 cmocka will_return() 将双精度值传递给我的 C 模拟函数?

问题描述 投票:0回答:2

我正在使用 cmocka 对 C 项目进行单元测试。

我想模拟对我正在测试的 C 函数中进行的另一个模块的调用。另一个模块中的此函数处理双精度数,而不是整数。

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() has converted this, effectively rounding
  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() will call other_func()
  ...
  assert(result == 0); 
  /* the assert is failing because the double 42.99 is converted to an integer,
     then back to a double, rounding off all the decimal places. */
}

> 42.0

有人知道如何使用

will_return
或其他 cmocka 方法将双精度数传递到模拟函数中吗?我被困在这个问题上。

我期望能够使用 cmocka 将非整数值传递给我的模拟函数。

当我尝试使用

will_return()
时,我发现所有双精度值都四舍五入为整数等值。

我仔细研究了 cmocka 文档并在线搜索了 cmocka 示例。

c unit-testing mocking cmocka
2个回答
0
投票

预期的方法是使用

will_return_float
mock_float

还有其他“分配”宏:

  • will_return_int
    mock_int
  • will_return_float
    mock_float
  • will_return_ptr
    mock_ptr
  • 等等

用来代替“铸造”宏

will_return
mock_type

旁注:

mock_float
不接受宏参数,到目前为止,它将值存储为
double


0
投票

我不认为 cmocka 本身提供 will_return_float 或 will_return_double 宏。我遇到了与您相同的问题,并且认为我找到了一种解决方法,涉及通过使用它来传递指向浮点的指针来“欺骗”mock() 宏。 (编辑:我刚刚意识到这正是https://stackoverflow.com/users/13199234/mem的评论) 不管怎样,以你的例子来说,那就是:

double __wrap_other_func(double param) {
  check_expected(param);
  double value = *(mock_type(double*)); // "value" takes the content of the double pointer! 
  fprintf(stderr, "%lf\n", value);
  return value;
}

static void test_this_func(void **state) {
  (void) state;
  double wantedResult = 42.99;  // define your wanted result
  expect_value(__wrap_other_func, param, 1.0);
  will_return(__wrap_other_func, &wantedResult);  // pass the pointer to the double value wantedResult instead of the value itself.
  int result = this_func(12.34); // this_func() will call other_func()
  ...

}

这条线

double value = *(mock_type(double*));

__wrap_other_func(double param)
的定义中 决心

double value = *((double*) &wantedResult;

wantedResult
相同。

请注意将 pointer 传递给

wantedResult
而不是
will_return
函数中的值的重要性。

© www.soinside.com 2019 - 2024. All rights reserved.