I have below class which I need to mock:
#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>));
};
I get below error:
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> ]
How can I mock the function in concern?
You need to perform sort of a trick as std::unique_ptr is move only class:
class MockCallBack : public Callback
{
public:
MOCK_METHOD1(mcallbackMock, void(int*));
void mcallback(std::unique_ptr<int> rpely)
{
mcallbackMock(rpely.get())
}
};
Then you can use it like this:
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
Also take a look at documentation Mocking Methods That Use Move-Only Types for more examples and more detailed explanation. (It seems that an earlier cookbook is now a broken link.)
A slightly lengthier example can be found in another SO answer to a question that was marked as a duplicate of this one. (It is hard to consider the titles duplicates, since one title mentions return values and the other mentions function arguments. But the content in the answers is essentially the same and covers both use cases: return types and function arguments.)