gtest Mock方法如何校验入参std::set中所有自定义结构体的指定字段值
正确实现方案
第一步:补全自定义结构体的比较运算符
std::set 要求存储的元素满足严格弱序规则,所以必须先为 my_struct 定义 operator<,否则连 std::set<my_struct> 本身都无法正常编译,这是最常见的编译错误原因。
补全后的结构体定义如下:
struct my_struct { int i; int j; int k; // 可根据实际业务逻辑调整排序规则 bool operator<(const my_struct& other) const { if (i != other.i) return i < other.i; if (j != other.j) return j < other.j; return k < other.k; } }; using my_set = std::set<my_struct>; MOCK_METHOD(void, my_func, (my_set));
第二步:编写正确的参数匹配规则
直接使用 GMock 内置的 Each + Field 匹配器组合即可实现需求,无需自定义 Matcher。注意要先引入对应匹配器的命名空间:
// 引入必要的匹配器命名空间 using ::testing::Each; using ::testing::Field; EXPECT_CALL(obj, my_func(Each(Field(&my_struct::i, 1)))) .Times(1);
匹配逻辑说明
Field(&my_struct::i, 1):匹配任意my_struct实例,要求其i字段取值等于1Each(...):要求传入的std::set容器中所有元素都满足括号内的匹配规则
如果需要同时校验多个字段,可以搭配AllOf匹配器使用:
using ::testing::AllOf; using ::testing::Each; using ::testing::Field; // 要求所有元素的i=1且j=2 EXPECT_CALL(obj, my_func(Each(AllOf( Field(&my_struct::i, 1), Field(&my_struct::j, 2) )))) .Times(1);
内容的提问来源于stack exchange,提问作者ekchom
相关产品推荐
相关产品推荐

