I am currently not succeding in mocking an interface that returns a 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 fails to compile because the Return
implementation makes a copy of the unique_ptr
Call &Return(Y obj) { retVal = new ReturnValueWrapper<Y>(obj); return *this; }
and the expectation attempts to return the 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've tried Do
, as suggested for a similar problem with returned references.
I've also tried writing my own ValueWrapper<T>
that generates a unique_ptr, but somewhere the value always gets copied. Right now I've run out of ideas.
One solution to the problem is to create a derived interface with an additional method that returns the return value as a temporary
and them modifying the original
ReturnValueHolder
to inherit from and implement the derived interface.
Once that has been done, the return from
DoExpectation
can be written asThe example from the question when rewritten to use
Do
then compiles and runs as expected.