MOCK接受unique_ptr的方法

时间:2018-08-06 09:06:35

标签: c++ gmock

我有下面的课需要模拟:

#include <gmock/gmock.h>
#include <gtest/gtest.h>
class Callback
{
public:
    Callback(): calls(0)
    {}
    void mcallback(std::unique_ptr<int> rpely)
    {
        calls++;
    }
    uint32_t calls;
};

class MockCallBack : public Callback
{
public:
    MOCK_METHOD1(mcallback, void(std::unique_ptr<int>));
};

我遇到以下错误:

error C2280: 'std::unique_ptr<int,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
1>        with
1>        [
1>            _Ty=int
1>        ]

如何模拟所关注的功能?

1 个答案:

答案 0 :(得分:0)

您需要执行一些技巧,因为std :: unique_ptr是仅移动类:

class MockCallBack : public Callback
{
public:
    MOCK_METHOD1(mcallbackMock, void(int*));

    void mcallback(std::unique_ptr<int> rpely)
    {
         mcallbackMock(rpely.get())
    }
};

然后您可以像这样使用它:

MockCallBack mockObject;
auto intPtr = std::make_unique<int>(3)

EXPECT_CALL(mockObject, mcallbackMock(NotNull())); //can use .Times(1) and other things as regular except call

mockObject.mcallback(intPtr); //will trigger except call above

还可以查看文档Mocking Methods That Use Move-Only Types,以获取更多示例和更详细的说明。