Can Google Mock a Method with a Smart Pointer Return Type

How to use a (smart) pointer to mocked object (in google mock)

Thanks to @YSC, @sklott and @Yksisarvinen that pointed me to the right direction.

For anyone having a similar issue. It turned out that in my case the issue was unrelated to the Google C++ mocking framework. I was passing the mock object to a derived class, whose base class's destructor was not declared as virtual. Therefore the destructor of the mock owner was never called and the mock object was kept alive.

Return reference to unique_ptr in google mock

The best fix would be to change the interface of BarInterface to return reference to BazInterface instead of reference unique_ptr. There is no need to expose the pointer to BarInterface users.

If you insist on returning reference to unique_ptr do it like this:

class BarMock : public BarInterface
{
public:
BarMock(std::unique_ptr<BazInterface> baz) {this->baz = std::move(baz);}

override std::unique_ptr<BazInterface>& getBaz(){
getBazWrapped();
return baz;
}
MOCK_METHOD0(getBazWrapped, void());
private:
std::unique_ptr<BazInterface> baz;
};

And in FooTest

BazMock * bazMock { new <StrictMock<BazMock> };
BarMock barMock { std::unique_ptr<BazInterface>(bazMock)};

MOCK a method that accepts unique_ptr

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.)



Related Topics



Leave a reply



Submit