Dependency injection with unique_ptr to mock

前端 未结 3 1076
终归单人心
终归单人心 2020-11-30 12:57

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

3条回答
  •  再見小時候
    2020-11-30 13:10

    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
    }
    

提交回复
热议问题