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

如何在GoogleTest中复用::testing::Values生成器(非宏/内部API)

解决方案:用inline函数封装可复用的参数生成器

你可以通过inline函数封装重复使用的::testing::Values(0,42,4711)生成器,完全避开宏和GoogleTest内部API,同时实现代码复用。

具体实现

在一个公共头文件中定义这个inline函数:

#include <gtest/gtest.h>

// C++14及以上版本可使用auto返回类型
inline auto CommonTestValues() {
    return ::testing::Values(0, 42, 4711);
}

// 如果是C++11,显式指定返回类型
// inline ::testing::ParamGenerator<int> CommonTestValues() {
//     return ::testing::Values(0, 42, 4711);
// }

调用方式

  • 单独使用生成器:
INSTANTIATE_TEST_SUITE_P(
    SingleParamTests,
    MyTestFixture,
    CommonTestValues()
);
  • 与::testing::Combine结合使用:
INSTANTIATE_TEST_SUITE_P(
    CombinedParamTests,
    CombinedTestFixture,
    ::testing::Combine(
        CommonTestValues(),
        ::testing::Values("option1", "option2")
    )
);

为什么constexpr不行?

::testing::Values返回的ParamGenerator对象是一个带内部状态的类实例,它的构造函数并非constexpr,因此无法用constexpr变量存储这个生成器实例。而inline函数每次调用都会生成一个新的合法ParamGenerator,效果和直接写::testing::Values(0,42,4711)完全一致,同时实现了代码复用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:27:43