您可以实现自己的匹配器obj
struct.
当您输入:
EXPECT_CALL(*mockedPointer, functionNeedsToBeMocked(some_obj)).Times(1).WillOnce(Return(true));
然后 gmock 使用默认匹配器,Eq
, using some_obj
作为其预期参数和实际参数functionNeedsToBeMocked
论证为arg
在匹配器中。Eq
匹配器将默认调用bool operator==
对于预期对象和实际对象:
EXPECT_CALL(*mockedPointer, functionNeedsToBeMocked(Eq(some_obj))).Times(1).WillOnce(Return(true));
但是,由于您不想使用bool operator==
,您可以编写一个自定义匹配器(删除Times(1)
因为它也是默认的):
// arg is passed to the matcher implicitly
// arg is the actual argument that the function was called with
MATCHER_P3(CustomObjMatcher, a, str, str2, "") {
return arg.a == a and arg.str == str and (arg.str2.find(str2) != std::string::npos);
}
[...]
EXPECT_CALL(*mockedPointer, functionNeedsToBeMocked(CustomObjMatcher(1, "test", "first"))).WillOnce(Return(true));
可以使用 来编写自定义匹配器Field
匹配器和内置匹配器为HasString
但让我们“把它作为练习留给读者”:P
更新:完整的代码Field
匹配器:
struct obj {
int a;
std::string str;
std::string str2;
};
struct Mock {
MOCK_METHOD(bool, functionNeedsToBeMocked, (obj&));
};
// creates a matcher for `struct obj` that matches field-by-field
auto Match(int expected_a, std::string expected_str1, std::string expected_substr2) {
return testing::AllOf(
testing::Field(&obj::a, expected_a),
testing::Field(&obj::str, expected_str1),
testing::Field(&obj::str2, testing::HasSubstr(expected_substr2))
);
}
TEST(MyTest, test) {
Mock mock{};
obj inputFirst;
inputFirst.a = 1;
inputFirst.str = "test";
inputFirst.str2 = "something first";
EXPECT_CALL(mock, functionNeedsToBeMocked(Match(1, "test", "first"))).Times(1).WillOnce(Return(true));
mock.functionNeedsToBeMocked(inputFirst);
}