我可以在设置期望后复制谷歌模拟对象吗?

nap*_*con 6 c++ unit-testing googletest googlemock

我想在我的测试夹具类中添加一个实用函数,该函数将返回具有特定期望/操作集的模拟。

\n\n

例如:

\n\n
class MockListener: public Listener\n{\n    // Google mock method.\n};\n\nclass MyTest: public testing::Test\n{\npublic:\n    MockListener getSpecialListener()\n    {\n        MockListener special;\n        EXPECT_CALL(special, /** Some special behaviour e.g. WillRepeatedly(Invoke( */ );\n        return special;\n    }\n};\n\nTEST_F(MyTest, MyTestUsingSpecialListener)\n{\n    MockListener special = getSpecialListener();\n\n    // Do something with special.\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

不幸的是我得到:

\n\n
error: use of deleted function \xe2\x80\x98MockListener ::MockListener (MockListener &&)\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以我认为模拟不能被复制?为什么,如果是的话,是否有另一种优雅的方式来获得一个函数来制造一个已经设置了期望/动作的现成的模拟?

\n\n

显然我可以让 getSpecialListener 返回一个 MockListener& ,但是这样它就不必要成为 MyTest 的成员,并且因为只有一些测试使用该特定的模拟(并且如果测试正在使用它,我应该只填充模拟行为)它会不太干净。

\n

Vla*_*sev 4

模拟对象是不可复制的,但您可以编写一个工厂方法来返回指向新创建的模拟对象的指针。为了简化对象所有权,您可以使用std::unique_ptr.

std::unique_ptr<MockListener> getSpecialListener() {
  MockListener* special = new MockListener();
  EXPECT_CALL(*special, SomeMethod()).WillRepeatedly(DoStuff());
  return std::unique_ptr<MockListener>(special);
}

TEST_F(MyTest, MyTestUsingSpecialListener) {
  std::unique_ptr<MockListener> special = getSpecialListener();

  // Do something with *special.
}
Run Code Online (Sandbox Code Playgroud)