I want to add a utility function in my test fixture class that will return a mock with particular expectations/actions set.
E.g.:
class MockListener: public Listener
{
// Google mock method.
};
class MyTest: public testing::Test
{
public:
MockListener getSpecialListener()
{
MockListener special;
EXPECT_CALL(special, /** Some special behaviour e.g. WillRepeatedly(Invoke( */ );
return special;
}
};
TEST_F(MyTest, MyTestUsingSpecialListener)
{
MockListener special = getSpecialListener();
// Do something with special.
}
Unfortunately I get:
error: use of deleted function ‘MockListener ::MockListener (MockListener &&)’
So I assume mocks can't be copied? Why, and if so is there another elegant way to get a function to manufacture a ready-made mock with expectations/actions already set?
Obviously I can make the getSpecialListener return a MockListener&, but then it would unnecessarily need to be a member of MyTest, and since only some of the tests use that particular mock (and I should only populate the mock behaviour if the test is using it) it would be less clean.
Mock objects are non-copyable, but you can write a factory method that returns a pointer to a newly created mock object. To simplify the object ownership, you can use 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.
}