HippoMocks - makes fun of a function that returns unique_ptr

I currently do not succeed in the mocking interface that returns unique_ptr. For example, given

struct IFoo { virtual std::unique_ptr<IFoo> foo = 0; }; int main() { MockRepository mocks; auto foo = mocks.Mock<IFoo>(); mocks.OnCall( foo, IFoo::foo ) .Return( std::unique_ptr<IFoo>() ); } 

This does not compile because the Return implementation creates a copy of unique_ptr

 Call &Return(Y obj) { retVal = new ReturnValueWrapper<Y>(obj); return *this; } 

and wait is trying to return unique_ptr

 template <typename Z> Z MockRepository::DoExpectation(base_mock *mock, std::pair<int, int> funcno, const base_tuple &tuple) { ... return ((ReturnValueWrapper<Z> *)call->retVal)->rv; } 

I tried Do , as suggested for a similar problem with returned links .

I also tried writing my own ValueWrapper<T> , which generates unique_ptr, but somewhere the value is always copied. I'm out of ideas right now.

+6
source share
1 answer

One solution to the problem is to create a derived interface with an additional method that returns the return value as temporary

 template <class T> class TypedReturnValueHolder : public ReturnValueHolder { public: virtual T rv() = 0; }; 

and they modify the original ReturnValueHolder

 template <class T> class ReturnValueWrapper : public ReturnValueHolder { public: typename no_cref<T>::type rv; ReturnValueWrapper(T rv) : rv(rv) {} }; 

to inherit and implement a derived interface.

 template <class T> class ReturnValueWrapper : public TypedReturnValueHolder<T> { typename no_cref<T>::type prv; public: ReturnValueWrapper(T rv) : prv(rv) {} virtual T rv() { return prv; }; }; 

Once this is done, the return from DoExpectation can be written as

  if (call->retVal) return ((TypedReturnValueHolder<Z> *)call->retVal)->rv(); 

Example from rewriting question for using Do

 mocks.OnCall( foo, IFoo::foo ) .Do( [](){ return std::unique_ptr<IFoo>(); } ); 

then compiled and executed as expected.

+2
source

All Articles