如何使用 Gmock 模拟没有 operator== 的函数参数

How to mock a Function arguments with no operator== using Gmock

我正在使用 Gmock 进行单元测试。 我有接收 protobuf 消息作为参数的函数。 问题是,当我用期望值测试函数时,它给我一个缺少运算符==的错误。 我在这里发现了类似的问题 google-protocol-buffers-compare

class ClientReaderWriterMock : public ClientReaderWriterIf {
 public:
  virtual ~ClientReaderWriterMock() = default;
  MOCK_METHOD1(Write, bool(const Msg&));
  MOCK_METHOD1(Read, bool(Msg*));
};

TEST_F(controller_Test, receive_message) {
Msg msg;
.
.
.
EXPECT_CALL(*clientReaderWriterMockObj, Write(msg));
.
.
.
}

我收到以下错误:

###>/third_party/googletest/googletest/include/gtest/gtest-matchers.h: In instantiation of ‘bool testing::internal::AnyEq::operator()(const A&, const B&) const [with A = Msg; B = Msg]’: /###>/third_party/googletest/googletest/include/gtest/gtest-matchers.h:549:18: required from ‘bool testing::internal::ComparisonBase<D, Rhs, Op>::Impl<Lhs, >::MatchAndExplain(Lhs, testing::MatchResultListener*) const [with Lhs = const Msg&; = Msg; D = testing::internal::EqMatcher; Rhs = Msg; Op = testing::internal::AnyEq]’ /###>/third_party/googletest/googletest/include/gtest/gtest-matchers.h:547:10: required from here /###>/third_party/googletest/googletest/include/gtest/gtest-matchers.h:211:60: error: no match for ‘operator==’ (operand types are ‘const Msg’ and ‘const Msg’) 211 | bool operator()(const A& a, const B& b) const { return a == b; } In file included from /###>/tests/unit/test.cpp:2: /###>/third_party/googletest/googletest/include/gtest/gtest.h:1535:13: note: candidate: ‘bool testing::internal::operator==(testing::internal::faketype, testing::internal::faketype)’ 1535 | inline bool operator==(faketype, faketype) { return true; } /###>/third_party/googletest/googletest/include/gtest/gtest.h:1535:24: note: no known conversion for argument 1 from ‘const Msg’ to ‘testing::internal::faketype’ 1535 | inline bool operator==(faketype, faketype) { return true; }

当对带有一些参数的函数设置 expect 调用时,会(隐式)使用 Eq 匹配器,因此行:

EXPECT_CALL(*clientReaderWriterMockObj, Write(msg));

实际上是:

EXPECT_CALL(*clientReaderWriterMockObj, Write(Eg(msg)));

Eq 匹配器将尝试调用 operator==(如您所见,它已丢失)。在这种情况下,您可以定义自己的匹配器:

MATCHER_P(CustomMatcher, expected, "Msg doesn't match!") {
    // your comparision code here
    return arg.Field() == expected.Field();
}
[...]
EXPECT_CALL(*clientReaderWriterMockObj, Write(CustomMatcher(msg)));