c++ - 使用Gmock调用成员函数

标签 c++ googlemock

这是我第一次使用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函数的参数中的 vector ,如何使用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

关于c++ - 使用Gmock调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64026618/

相关文章:

c++ - map 数组帮助c++/qt

c++ - 不占用物理内存的静态局部变量

c++ - OpenCL 中的 memset 局部变量/内存

c++ - GoogleMock:如何验证输入参数 w.r.t 调用次数?

c++ - 使用 googlemock 时,我可以不模拟 C++ 接口(interface)中的所有方法吗?

c++ - 如何为具有多个模块(包括单元测试等)的项目设置 cmake

c++ - QGroupBox 内的 QScrollArea,滚动条而不是调整 QGroupBox 的大小

c++ - 用更大的 vector 覆盖 vector 的最有效方法

c++ - 检查容器元素之间关系的 googletest 匹配器

c++ - Google-Mock 一个已经声明的方法