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

如何用GoogleTest测试含引用成员的结构体字段?

GoogleTest测试含引用类型成员的结构体字段的解决方法

当结构体成员为引用类型时,直接使用testing::Field会触发编译错误——C++不允许创建引用成员的指针,报错信息为error: cannot create pointer to reference member 'Thing::b'。在无法修改结构体定义的前提下,可通过testing::Property替代testing::Field实现单个字段的测试。

解决方案示例

保持原结构体定义不变:

struct Thing {
    const std::string& a;
    const std::string& b;
};

方法1:使用Lambda表达式

直接在Property中传入lambda获取引用成员的值:

TEST(Test, test1)
{
    testing::StrictMock<testing::MockFunction<void(const Thing &)>> callback;
    Thing t {"aaa", "bbb"}; // 实际场景无法直接访问t,此处仅作示例
    {
        EXPECT_CALL(callback, Call(testing::Property(
            [](const Thing& thing) -> const std::string& { return thing.b; },
            testing::Eq("bbb")
        )));
        callback.AsStdFunction()(t);
    }
}

方法2:使用辅助函数

若需复用成员获取逻辑,可提取为独立辅助函数:

const std::string& GetThingB(const Thing& thing) {
    return thing.b;
}

TEST(Test, test2)
{
    testing::StrictMock<testing::MockFunction<void(const Thing &)>> callback;
    Thing t {"aaa", "bbb"};
    {
        EXPECT_CALL(callback, Call(testing::Property(&GetThingB, testing::Eq("bbb"))));
        callback.AsStdFunction()(t);
    }
}

原理说明

testing::Property接受两个参数:第一个是可调用对象(lambda/函数指针),负责接收被测对象引用并返回需检查的成员值;第二个是对返回值的匹配器(如Eq)。这种方式无需获取引用成员的指针,既绕过了编译限制,又满足仅检查单个字段的测试需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:55:19