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

如何读取GoogleMock模拟方法传入的数组指针内容?

解决GoogleMock中验证数组指针参数所有元素的问题

问题根源

  • SaveArgPointee<1>(passed_array)仅会复制指针指向的第一个元素,所以passed_array只有第一个元素被赋值,其余保持初始值。
  • SetArrayArgument<1>(...)的作用是让模拟函数向参数指针写入数据,而非读取传入的数组内容,因此用反了方向,导致passed_array无变化。

解决方案

方法一:保存数组指针后手动复制元素

先通过SaveArg获取传入的数组指针,再手动复制所有元素到目标数组:

TEST_F(InterfaceTest, TestFuncInterfacePointerArgs) {
  MockFortranFuncInterfacePointerArgs mock_func_interface;
  int passed_scalar = 0;
  int passed_array[3] = {0, 0, 0};
  int* array_ptr = nullptr; // 用于保存传入的数组指针

  EXPECT_CALL(mock_func_interface, fortran_interface_test_func_pointerargs(testing::_, testing::_))
    .WillOnce(testing::DoAll(
        testing::SaveArgPointee<0>(&passed_scalar),
        testing::SaveArg<1>(&array_ptr) // 保存数组指针
    ));

  testfunc_pointer(&mock_func_interface);

  // 手动复制数组元素
  if (array_ptr != nullptr) {
    std::copy(array_ptr, array_ptr + 3, passed_array);
  }

  // 验证结果
  EXPECT_EQ(passed_scalar, 123);
  EXPECT_THAT(passed_array, testing::ElementsAre(1, 2, 3));
  
  std::cout << passed_scalar << std::endl;
  std::cout << passed_array[0] << " " << passed_array[1] << " " << passed_array[2] << std::endl;
}

方法二:自定义动作直接复制数组

用Lambda表达式定义自定义动作,在模拟函数被调用时直接完成数组复制:

TEST_F(InterfaceTest, TestFuncInterfacePointerArgs) {
  MockFortranFuncInterfacePointerArgs mock_func_interface;
  int passed_scalar = 0;
  int passed_array[3] = {0, 0, 0};

  EXPECT_CALL(mock_func_interface, fortran_interface_test_func_pointerargs(testing::_, testing::_))
    .WillOnce(testing::DoAll(
        testing::SaveArgPointee<0>(&passed_scalar),
        // 自定义动作:复制数组的3个元素
        testing::Invoke([&](int*, int* arr_ptr) {
          std::copy(arr_ptr, arr_ptr + 3, passed_array);
        })
    ));

  testfunc_pointer(&mock_func_interface);

  EXPECT_EQ(passed_scalar, 123);
  EXPECT_THAT(passed_array, testing::ElementsAre(1, 2, 3));
  
  std::cout << passed_scalar << std::endl;
  std::cout << passed_array[0] << " " << passed_array[1] << " " << passed_array[2] << std::endl;
}

说明

两种方法都不需要修改testfunc_pointer函数,核心是正确获取传入的数组指针并复制所有元素。testing::ElementsAre是GoogleTest提供的断言,用于验证数组元素是否符合预期,比手动打印更适合自动化测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:53:33