title: How can I mock a method with a return type of unique_ptr in Google Mock?
body: <p>I have read <a href="https://stackoverflow.com/questions/7616475/can-google-mock-a-method-with-a-smart-pointer-return-type">Can Google Mock a method with a smart pointer return type?</a> but it did not really give much of an answer.</p>
  
  <p>I have a factory that returns unique_ptr instances. Returning unique_ptr is a requirement that cannot change without really good reason and a discussion with those above my pay grade (which I am willing to do if it plain turns out you should not be returning these things).</p>
  
  <p>In the code being tested, there are three objects in question. The first is a handler of sorts. Using that handler, you can create the second object, which is the only real interesting one after everything is said and done. But creating that second one is a complex process that requires extra work done by the specific handler instance, as well as a factory (the third object) to take care of logic needed in creating Mr. Second regardless of handler requirements.</p>
  
  <p>Here's the testing code in question (with class names changed in order to avoid HR hell):</p>
  
  <pre><code>class BarTest : public ::testing::Test
  {
  protected:
      Bar foo;
  };
  
  TEST_F(BarTest, createFoo)
  {
      // Data used in this test
      std::string fooName = "test";
      MockFooFactory&lt;int&gt; fooFactory;
  
      MockFoo&lt;int&gt;* foo = new MockFoo&lt;int&gt;;
  
      // When createFoo is called, it should call the foo factory's construct method with the given
      // fooName and a pointer to the calling bar
      EXPECT_CALL(fooFactory, construct(fooName, &amp;bar)).
          WillOnce(::testing::Return(std::unique_ptr&lt;Foo&lt;int&gt;&gt;(foo)));
  
      // Test it
      std::unique_ptr&lt;Foo&lt;int&gt;&gt; returnedFoo = bar.createFoo(fooName, fooFactory);
  
      // createFoo should return the foo returned by the factory's construct method
      ASSERT_EQ(foo, returnedFoo.get());
  }
  </code></pre>
  
  <p>As one might expect, upon compiling this (specifically with GCC) the compiler complains about using the deleted copy constructor. I do not think there is a way to finagle this around in order to impose move semantics (at the very least not through the admittedly naive approaches I tried), and just telling it to return the raw pointer and hoping it can wrap it up itself also failed (potentially naive as well), so I am stuck.</p>
  
  <p>At this point I am really leaning towards making a fake, but I would like to give it one last shot with pure mocking. If there is some way I can get this return to work, that would be fantastic. Either way, I have full control over the mocking and testing, so as long as this case gets covered (hopefully without hackiness) how direct or indirect the approach is not a concern.</p>