简体   繁体   中英

Copiable mocks in Google Test Framework

Is it possible to make a mock class copiable in Google Test Framework ? I've seen that the default copy constructor and copy assignment operator are deleted once that the MOCK_METHOD macros are used. Is there a way to workaround that?

I cannot imagine any use case for copying mock objects. When you want to mimic real object with mock object - you shall have access to the very same object from code under test and from your test case code - so why copying needed?

Anyway - I see one method to make copying of mock object: You have to define wrapper on mock object - which shall be kept by std::shared_ptr .

An example:

class XxxMock : public XxxInterface
{
public:
   MOCK_METHOD0(foo, void());
};

#include <memory>
class XxxSharedMock : public XxxInteface
{
public:
   XxxSharedMock(std::shared_ptr<XxxMock> xxxMock = std::make_shared<XxxMock>())
      : xxxMock(xxxMock) 
   {}
   void foo() override
   {
       xxxMock->foo();
   }
   // having: XxxSharedMock xxxMock; 
   // do:     EXPECT_CALL(xxxMock.mock(), foo());
   XxxMock& mock() { return *xxxMock; }
   XxxMock const& mock() const { return *xxxMock; }

privated:
   std::shared_ptr<XxxMock> xxxMock;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM