如何解决使用Gmock调用成员函数
这是我第一次使用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);
时,我需要_testVec填充传递给func
函数的参数中的向量,如何使用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
将把模拟接收的所有参数传递给调用的函数,并且它必须返回与模拟函数相同的类型。如果您希望不使用args,请使用InvokeWithoutArgs
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。