Matthew Reddington Matthew Reddington - 1 year ago 276
C++ Question

Can Google Mock a method with a smart pointer return type?

I have a factory that returns a smart pointer. Regardless of what smart pointer I use, I can't get Google Mock to mock the factory method.

The mock object is the implementation of a pure abstract interface where all methods are virtual. I have a prototype:

MOCK_METHOD0(Create, std::unique_ptr<IMyObjectThing>());

And I get:

"...gmock/gmock-spec-builders.h(1314): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'"

The type pointed to in the smart pointer is defined.

And I get it's trying to access one of the constructors declared private, but I don't understand why. When this was an std::auto_ptr, the error said there was no copy constructor, which confuses me.

Anyway, is there a way to Mock a method that returns a smart pointer? Or is there a better way to build a factory? Is my only resolve to return a raw pointer (blech...)?

My environment is Visual Studio 2010 Ultimate and Windows 7. I'm not using CLI.

Answer Source

Google Mock requires parameters and return values of mocked methods to be copyable, in most cases. Per boost's documentation, unique_ptr is not copyable. You have an option of returning one of the smart pointer classes that use shared ownership (shared_ptr, linked_ptr, etc.) and are thus copyable. Or you can use a raw pointer. Since the method in question is apparently the method constructing an object, I see no inherent problem with returning a raw pointer. As long as you assign the result to some shared pointer at every call site, you are going to be fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download