使用GMock 1.21模拟含std::vector<RECT>参数的方法遇编译错误
解决GMock模拟含RECT容器参数方法的编译错误
问题核心:GMock在匹配EXPECT_CALL的参数时,需要参数类型支持相等比较(默认使用std::equal_to)。Windows的RECT结构体没有默认重载==运算符,导致编译时无法特化std::equal_to,报error C2893错误。
以下是几种可行的解决方法:
方法1:为RECT重载==运算符
在测试代码或全局可见的头文件中添加运算符重载,让GMock能直接比较RECT对象:
#include <windef.h> // 重载RECT的相等比较运算符 bool operator==(const RECT& lhs, const RECT& rhs) { return lhs.left == rhs.left && lhs.top == rhs.top && lhs.right == rhs.right && lhs.bottom == rhs.bottom; }
添加后,原测试代码中的EXPECT_CALL(mock, DisplayRect(v))就能正常工作,GMock会自动递归比较VRECT(即std::vector<RECT>)中的每个元素。
方法2:使用GMock内置匹配器跳过或精准匹配参数
如果不想全局重载运算符,可以用GMock的匹配器替代直接传参:
- 忽略参数具体值,只验证方法被调用:
EXPECT_CALL(mock, DisplayRect(::testing::_)).WillRepeatedly(::testing::Return(true)); - 精准匹配容器中的RECT元素:
用Field匹配器检查RECT的每个成员:EXPECT_CALL(mock, DisplayRect(::testing::Contains(::testing::AllOf( ::testing::Field(&RECT::left, 10), ::testing::Field(&RECT::top, 20), ::testing::Field(&RECT::right, 30), ::testing::Field(&RECT::bottom, 40) )))).WillRepeatedly(::testing::Return(true));
方法3:自定义GMock匹配器
用MATCHER_P宏定义专属的RECT匹配器,灵活性更高:
#include <gmock/gmock.h> #include <windef.h> // 自定义匹配器:判断两个RECT是否相等 MATCHER_P(EqualsRect, expected, "") { return arg.left == expected.left && arg.top == expected.top && arg.right == expected.right && arg.bottom == expected.bottom; } // 在测试中使用 TEST(Testing, Case1) { MockCXRECT mock; VRECT v; RECT testRect = {10,20,30,40}; v.push_back(testRect); EXPECT_CALL(mock, DisplayRect(::testing::Contains(EqualsRect(testRect)))) .WillRepeatedly(::testing::Return(true)); }
注:替换为int等简单类型时正常,是因为这类基础类型本身就支持==运算符,GMock无需额外处理。
内容的提问来源于stack exchange,提问作者kishoredbn
相关产品推荐
相关产品推荐

