使用Gmock调用成员函数

using Gmock to call a member function

本文关键字:函数 成员 调用 Gmock 使用      更新时间:2024-04-28

这是我第一次使用gmock,并拥有Mock类的示例

class MockInterface : public ExpInterface
{
public:
MockInterface() : ExpInterface() 
{
ON_CALL(*this, func(testing::_)).WillByDefault(testing::Invoke([this]() {
// I need to fill the testVec with the vector passed as parameter to func
return true; }));
}
MOCK_METHOD1(func, bool(const std::vector<int>&));
~MockInterface() = default;
private:
std::vector<int> _testVec;
};

然后我创建了一个MockInterface 的实例

auto mockInt = std::make_shared<MockInterface>();

当调用mockInt->func(vec);时,我需要用传递给func函数的参数来填充_testVec,如何用gMock来做这种事情?

您可以使用SaveArg操作:

ON_CALL(*this, func(::testing::_)).WillByDefault(
::testing::DoAll(
::testing::SaveArg<0>(&_testVec),
::testing::Return(false)));

如果要调用成员函数,可以使用lambda或指向成员语法的指针。

ON_CALL(*this, func(::testing::_)).WillByDefault(
::testing::Invoke(this, &MockInterface::foo);
ON_CALL(*this, func(::testing::_)).WillByDefault(
::testing::Invoke([this](const std::vector& arg){ return foo();});

请记住,Invoke将把mock接收到的所有参数传递给被调用的函数,并且它必须返回与mock函数相同的类型。如果您希望它不带args,请使用InvokeWithoutArgs