I have a class Foo that uses class Bar. Bar is used only in Foo and Foo is managing Bar, therefore I use unique_ptr (not a reference, because I don\'t need Bar outside of Fo
You can keep a reference to the mocked object before passing it to the constructor. I think it makes the code a tad bit brittle, due to member initialization ordering, but it is clearer semantically what it means. Ownership of BarMock still belongs solely to Foo, with a reference handle kept by FooTest (similar to this answer).
Basically the same as your answer, but using reference instead of a raw pointer
class FooTest : public ::testing::Test
{
protected:
FooTest() :
bar_mock_ptr(std::make_unique()),
bar_mock(*bar_mock_ptr),
foo(std::move(bar_mock_ptr))
{}
private:
// This must be declared before bar_mock due to how member initialization is ordered
std::unique_ptr bar_mock_ptr; // moved and should not be used anymore
protected:
BarMock& bar_mock;
Foo foo; //ensure foo has the same lifetime as bar_mock
}