首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Gmock调用成员函数

使用Gmock调用成员函数
EN

Stack Overflow用户
提问于 2020-09-23 19:08:55
回答 1查看 99关注 0票数 1

这是我第一次使用gmock,并且有这个Mock类的例子

代码语言:javascript
复制
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的一个实例

代码语言:javascript
复制
auto mockInt = std::make_shared<MockInterface>();

当调用mockInt->func(vec);时,我需要用传递给func函数的向量填充_testVec,如何使用gMock完成这类工作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-23 19:25:46

您可以改用SaveArg操作:

代码语言:javascript
复制
ON_CALL(*this, func(::testing::_)).WillByDefault(
    ::testing::DoAll(
        ::testing::SaveArg<0>(&_testVec),
        ::testing::Return(false)));

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

代码语言:javascript
复制
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将把模拟接收到的所有参数传递给被调用的函数,并且它必须返回与模拟函数相同的类型。如果您希望它不带参数,请使用InvokeWithoutArgs

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64026618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档