nap*_*con 6 c++ unit-testing googletest googlemock
我想在我的测试夹具类中添加一个实用函数,该函数将返回具有特定期望/操作集的模拟。
\n\n例如:
\n\nclass 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}\nRun Code Online (Sandbox Code Playgroud)\n\n不幸的是我得到:
\n\nerror: use of deleted function \xe2\x80\x98MockListener ::MockListener (MockListener &&)\xe2\x80\x99\nRun Code Online (Sandbox Code Playgroud)\n\n所以我认为模拟不能被复制?为什么,如果是的话,是否有另一种优雅的方式来获得一个函数来制造一个已经设置了期望/动作的现成的模拟?
\n\n显然我可以让 getSpecialListener 返回一个 MockListener& ,但是这样它就不必要成为 MyTest 的成员,并且因为只有一些测试使用该特定的模拟(并且如果测试正在使用它,我应该只填充模拟行为)它会不太干净。
\n模拟对象是不可复制的,但您可以编写一个工厂方法来返回指向新创建的模拟对象的指针。为了简化对象所有权,您可以使用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)